clang 17.0.6
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
28#include "clang/AST/StmtCXX.h"
34#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
36#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
39#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/Lookup.h"
44#include "clang/Sema/Scope.h"
47#include "clang/Sema/Template.h"
48#include "llvm/ADT/SmallString.h"
49#include "llvm/ADT/StringExtras.h"
50#include "llvm/TargetParser/Triple.h"
51#include <algorithm>
52#include <cstring>
53#include <functional>
54#include <optional>
55#include <unordered_map>
56
57using namespace clang;
58using namespace sema;
59
61 if (OwnedType) {
62 Decl *Group[2] = { OwnedType, Ptr };
64 }
65
67}
68
69namespace {
70
71class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
72 public:
73 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
74 bool AllowTemplates = false,
75 bool AllowNonTemplates = true)
76 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
77 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
78 WantExpressionKeywords = false;
79 WantCXXNamedCasts = false;
80 WantRemainingKeywords = false;
81 }
82
83 bool ValidateCandidate(const TypoCorrection &candidate) override {
84 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
85 if (!AllowInvalidDecl && ND->isInvalidDecl())
86 return false;
87
89 return AllowTemplates;
90
91 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
92 if (!IsType)
93 return false;
94
95 if (AllowNonTemplates)
96 return true;
97
98 // An injected-class-name of a class template (specialization) is valid
99 // as a template or as a non-template.
100 if (AllowTemplates) {
101 auto *RD = dyn_cast<CXXRecordDecl>(ND);
102 if (!RD || !RD->isInjectedClassName())
103 return false;
104 RD = cast<CXXRecordDecl>(RD->getDeclContext());
105 return RD->getDescribedClassTemplate() ||
107 }
108
109 return false;
110 }
111
112 return !WantClassName && candidate.isKeyword();
113 }
114
115 std::unique_ptr<CorrectionCandidateCallback> clone() override {
116 return std::make_unique<TypeNameValidatorCCC>(*this);
117 }
118
119 private:
120 bool AllowInvalidDecl;
121 bool WantClassName;
122 bool AllowTemplates;
123 bool AllowNonTemplates;
124};
125
126} // end anonymous namespace
127
128/// Determine whether the token kind starts a simple-type-specifier.
130 switch (Kind) {
131 // FIXME: Take into account the current language when deciding whether a
132 // token kind is a valid type specifier
133 case tok::kw_short:
134 case tok::kw_long:
135 case tok::kw___int64:
136 case tok::kw___int128:
137 case tok::kw_signed:
138 case tok::kw_unsigned:
139 case tok::kw_void:
140 case tok::kw_char:
141 case tok::kw_int:
142 case tok::kw_half:
143 case tok::kw_float:
144 case tok::kw_double:
145 case tok::kw___bf16:
146 case tok::kw__Float16:
147 case tok::kw___float128:
148 case tok::kw___ibm128:
149 case tok::kw_wchar_t:
150 case tok::kw_bool:
151#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
152#include "clang/Basic/TransformTypeTraits.def"
153 case tok::kw___auto_type:
154 return true;
155
156 case tok::annot_typename:
157 case tok::kw_char16_t:
158 case tok::kw_char32_t:
159 case tok::kw_typeof:
160 case tok::annot_decltype:
161 case tok::kw_decltype:
162 return getLangOpts().CPlusPlus;
163
164 case tok::kw_char8_t:
165 return getLangOpts().Char8;
166
167 default:
168 break;
169 }
170
171 return false;
172}
173
174namespace {
175enum class UnqualifiedTypeNameLookupResult {
176 NotFound,
177 FoundNonType,
178 FoundType
179};
180} // end anonymous namespace
181
182/// Tries to perform unqualified lookup of the type decls in bases for
183/// dependent class.
184/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
185/// type decl, \a FoundType if only type decls are found.
186static UnqualifiedTypeNameLookupResult
188 SourceLocation NameLoc,
189 const CXXRecordDecl *RD) {
190 if (!RD->hasDefinition())
191 return UnqualifiedTypeNameLookupResult::NotFound;
192 // Look for type decls in base classes.
193 UnqualifiedTypeNameLookupResult FoundTypeDecl =
194 UnqualifiedTypeNameLookupResult::NotFound;
195 for (const auto &Base : RD->bases()) {
196 const CXXRecordDecl *BaseRD = nullptr;
197 if (auto *BaseTT = Base.getType()->getAs<TagType>())
198 BaseRD = BaseTT->getAsCXXRecordDecl();
199 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
200 // Look for type decls in dependent base classes that have known primary
201 // templates.
202 if (!TST || !TST->isDependentType())
203 continue;
204 auto *TD = TST->getTemplateName().getAsTemplateDecl();
205 if (!TD)
206 continue;
207 if (auto *BasePrimaryTemplate =
208 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
209 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
210 BaseRD = BasePrimaryTemplate;
211 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
213 CTD->findPartialSpecialization(Base.getType()))
214 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
215 BaseRD = PS;
216 }
217 }
218 }
219 if (BaseRD) {
220 for (NamedDecl *ND : BaseRD->lookup(&II)) {
221 if (!isa<TypeDecl>(ND))
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224 }
225 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
226 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
227 case UnqualifiedTypeNameLookupResult::FoundNonType:
228 return UnqualifiedTypeNameLookupResult::FoundNonType;
229 case UnqualifiedTypeNameLookupResult::FoundType:
230 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
231 break;
232 case UnqualifiedTypeNameLookupResult::NotFound:
233 break;
234 }
235 }
236 }
237 }
238
239 return FoundTypeDecl;
240}
241
243 const IdentifierInfo &II,
244 SourceLocation NameLoc) {
245 // Lookup in the parent class template context, if any.
246 const CXXRecordDecl *RD = nullptr;
247 UnqualifiedTypeNameLookupResult FoundTypeDecl =
248 UnqualifiedTypeNameLookupResult::NotFound;
249 for (DeclContext *DC = S.CurContext;
250 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
251 DC = DC->getParent()) {
252 // Look for type decls in dependent base classes that have known primary
253 // templates.
254 RD = dyn_cast<CXXRecordDecl>(DC);
255 if (RD && RD->getDescribedClassTemplate())
256 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
257 }
258 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
259 return nullptr;
260
261 // We found some types in dependent base classes. Recover as if the user
262 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
263 // lookup during template instantiation.
264 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
265
266 ASTContext &Context = S.Context;
267 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
268 cast<Type>(Context.getRecordType(RD)));
269 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
270
271 CXXScopeSpec SS;
272 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
273
274 TypeLocBuilder Builder;
275 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
276 DepTL.setNameLoc(NameLoc);
278 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
279 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
280}
281
282/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
284 SourceLocation NameLoc,
285 bool WantNontrivialTypeSourceInfo = true) {
286 switch (T->getTypeClass()) {
287 case Type::DeducedTemplateSpecialization:
288 case Type::Enum:
289 case Type::InjectedClassName:
290 case Type::Record:
291 case Type::Typedef:
292 case Type::UnresolvedUsing:
293 case Type::Using:
294 break;
295 // These can never be qualified so an ElaboratedType node
296 // would carry no additional meaning.
297 case Type::ObjCInterface:
298 case Type::ObjCTypeParam:
299 case Type::TemplateTypeParm:
300 return ParsedType::make(T);
301 default:
302 llvm_unreachable("Unexpected Type Class");
303 }
304
305 if (!SS || SS->isEmpty())
306 return ParsedType::make(
307 S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
308
309 QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
310 if (!WantNontrivialTypeSourceInfo)
311 return ParsedType::make(ElTy);
312
313 TypeLocBuilder Builder;
314 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
315 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
318 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
319}
320
321/// If the identifier refers to a type name within this scope,
322/// return the declaration of that type.
323///
324/// This routine performs ordinary name lookup of the identifier II
325/// within the given scope, with optional C++ scope specifier SS, to
326/// determine whether the name refers to a type. If so, returns an
327/// opaque pointer (actually a QualType) corresponding to that
328/// type. Otherwise, returns NULL.
330 Scope *S, CXXScopeSpec *SS, bool isClassName,
331 bool HasTrailingDot, ParsedType ObjectTypePtr,
332 bool IsCtorOrDtorName,
333 bool WantNontrivialTypeSourceInfo,
334 bool IsClassTemplateDeductionContext,
335 ImplicitTypenameContext AllowImplicitTypename,
336 IdentifierInfo **CorrectedII) {
337 // FIXME: Consider allowing this outside C++1z mode as an extension.
338 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
339 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
340 !isClassName && !HasTrailingDot;
341
342 // Determine where we will perform name lookup.
343 DeclContext *LookupCtx = nullptr;
344 if (ObjectTypePtr) {
345 QualType ObjectType = ObjectTypePtr.get();
346 if (ObjectType->isRecordType())
347 LookupCtx = computeDeclContext(ObjectType);
348 } else if (SS && SS->isNotEmpty()) {
349 LookupCtx = computeDeclContext(*SS, false);
350
351 if (!LookupCtx) {
352 if (isDependentScopeSpecifier(*SS)) {
353 // C++ [temp.res]p3:
354 // A qualified-id that refers to a type and in which the
355 // nested-name-specifier depends on a template-parameter (14.6.2)
356 // shall be prefixed by the keyword typename to indicate that the
357 // qualified-id denotes a type, forming an
358 // elaborated-type-specifier (7.1.5.3).
359 //
360 // We therefore do not perform any name lookup if the result would
361 // refer to a member of an unknown specialization.
362 // In C++2a, in several contexts a 'typename' is not required. Also
363 // allow this as an extension.
364 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
365 !isClassName && !IsCtorOrDtorName)
366 return nullptr;
367 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
368 if (IsImplicitTypename) {
369 SourceLocation QualifiedLoc = SS->getRange().getBegin();
371 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
372 else
373 Diag(QualifiedLoc, diag::ext_implicit_typename)
374 << SS->getScopeRep() << II.getName()
375 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
376 }
377
378 // We know from the grammar that this name refers to a type,
379 // so build a dependent node to describe the type.
380 if (WantNontrivialTypeSourceInfo)
381 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
382 (ImplicitTypenameContext)IsImplicitTypename)
383 .get();
384
386 QualType T =
387 CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
388 SourceLocation(), QualifierLoc, II, NameLoc);
389 return ParsedType::make(T);
390 }
391
392 return nullptr;
393 }
394
395 if (!LookupCtx->isDependentContext() &&
396 RequireCompleteDeclContext(*SS, LookupCtx))
397 return nullptr;
398 }
399
400 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
401 // lookup for class-names.
402 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
404 LookupResult Result(*this, &II, NameLoc, Kind);
405 if (LookupCtx) {
406 // Perform "qualified" name lookup into the declaration context we
407 // computed, which is either the type of the base of a member access
408 // expression or the declaration context associated with a prior
409 // nested-name-specifier.
410 LookupQualifiedName(Result, LookupCtx);
411
412 if (ObjectTypePtr && Result.empty()) {
413 // C++ [basic.lookup.classref]p3:
414 // If the unqualified-id is ~type-name, the type-name is looked up
415 // in the context of the entire postfix-expression. If the type T of
416 // the object expression is of a class type C, the type-name is also
417 // looked up in the scope of class C. At least one of the lookups shall
418 // find a name that refers to (possibly cv-qualified) T.
419 LookupName(Result, S);
420 }
421 } else {
422 // Perform unqualified name lookup.
423 LookupName(Result, S);
424
425 // For unqualified lookup in a class template in MSVC mode, look into
426 // dependent base classes where the primary class template is known.
427 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
428 if (ParsedType TypeInBase =
429 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
430 return TypeInBase;
431 }
432 }
433
434 NamedDecl *IIDecl = nullptr;
435 UsingShadowDecl *FoundUsingShadow = nullptr;
436 switch (Result.getResultKind()) {
439 if (CorrectedII) {
440 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
441 AllowDeducedTemplate);
442 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
443 S, SS, CCC, CTK_ErrorRecovery);
444 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
445 TemplateTy Template;
446 bool MemberOfUnknownSpecialization;
448 TemplateName.setIdentifier(NewII, NameLoc);
450 CXXScopeSpec NewSS, *NewSSPtr = SS;
451 if (SS && NNS) {
452 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
453 NewSSPtr = &NewSS;
454 }
455 if (Correction && (NNS || NewII != &II) &&
456 // Ignore a correction to a template type as the to-be-corrected
457 // identifier is not a template (typo correction for template names
458 // is handled elsewhere).
459 !(getLangOpts().CPlusPlus && NewSSPtr &&
460 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
461 Template, MemberOfUnknownSpecialization))) {
462 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
463 isClassName, HasTrailingDot, ObjectTypePtr,
464 IsCtorOrDtorName,
465 WantNontrivialTypeSourceInfo,
466 IsClassTemplateDeductionContext);
467 if (Ty) {
468 diagnoseTypo(Correction,
469 PDiag(diag::err_unknown_type_or_class_name_suggest)
470 << Result.getLookupName() << isClassName);
471 if (SS && NNS)
472 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
473 *CorrectedII = NewII;
474 return Ty;
475 }
476 }
477 }
478 // If typo correction failed or was not performed, fall through
479 [[fallthrough]];
482 Result.suppressDiagnostics();
483 return nullptr;
484
486 // Recover from type-hiding ambiguities by hiding the type. We'll
487 // do the lookup again when looking for an object, and we can
488 // diagnose the error then. If we don't do this, then the error
489 // about hiding the type will be immediately followed by an error
490 // that only makes sense if the identifier was treated like a type.
491 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
492 Result.suppressDiagnostics();
493 return nullptr;
494 }
495
496 // Look to see if we have a type anywhere in the list of results.
497 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
498 Res != ResEnd; ++Res) {
499 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
500 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
501 RealRes) ||
502 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
503 if (!IIDecl ||
504 // Make the selection of the recovery decl deterministic.
505 RealRes->getLocation() < IIDecl->getLocation()) {
506 IIDecl = RealRes;
507 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
508 }
509 }
510 }
511
512 if (!IIDecl) {
513 // None of the entities we found is a type, so there is no way
514 // to even assume that the result is a type. In this case, don't
515 // complain about the ambiguity. The parser will either try to
516 // perform this lookup again (e.g., as an object name), which
517 // will produce the ambiguity, or will complain that it expected
518 // a type name.
519 Result.suppressDiagnostics();
520 return nullptr;
521 }
522
523 // We found a type within the ambiguous lookup; diagnose the
524 // ambiguity and then return that type. This might be the right
525 // answer, or it might not be, but it suppresses any attempt to
526 // perform the name lookup again.
527 break;
528
530 IIDecl = Result.getFoundDecl();
531 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
532 break;
533 }
534
535 assert(IIDecl && "Didn't find decl");
536
537 QualType T;
538 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
539 // C++ [class.qual]p2: A lookup that would find the injected-class-name
540 // instead names the constructors of the class, except when naming a class.
541 // This is ill-formed when we're not actually forming a ctor or dtor name.
542 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
543 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
544 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
545 FoundRD->isInjectedClassName() &&
546 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
547 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
548 << &II << /*Type*/1;
549
550 DiagnoseUseOfDecl(IIDecl, NameLoc);
551
552 T = Context.getTypeDeclType(TD);
553 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
554 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
555 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
556 if (!HasTrailingDot)
557 T = Context.getObjCInterfaceType(IDecl);
558 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
559 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
560 (void)DiagnoseUseOfDecl(UD, NameLoc);
561 // Recover with 'int'
563 } else if (AllowDeducedTemplate) {
564 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
565 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
566 TemplateName Template =
567 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
569 false);
570 // Don't wrap in a further UsingType.
571 FoundUsingShadow = nullptr;
572 }
573 }
574
575 if (T.isNull()) {
576 // If it's not plausibly a type, suppress diagnostics.
577 Result.suppressDiagnostics();
578 return nullptr;
579 }
580
581 if (FoundUsingShadow)
582 T = Context.getUsingType(FoundUsingShadow, T);
583
584 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
585}
586
587// Builds a fake NNS for the given decl context.
588static NestedNameSpecifier *
590 for (;; DC = DC->getLookupParent()) {
591 DC = DC->getPrimaryContext();
592 auto *ND = dyn_cast<NamespaceDecl>(DC);
593 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
594 return NestedNameSpecifier::Create(Context, nullptr, ND);
595 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
596 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
597 RD->getTypeForDecl());
598 else if (isa<TranslationUnitDecl>(DC))
600 }
601 llvm_unreachable("something isn't in TU scope?");
602}
603
604/// Find the parent class with dependent bases of the innermost enclosing method
605/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
606/// up allowing unqualified dependent type names at class-level, which MSVC
607/// correctly rejects.
608static const CXXRecordDecl *
610 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
611 DC = DC->getPrimaryContext();
612 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
613 if (MD->getParent()->hasAnyDependentBases())
614 return MD->getParent();
615 }
616 return nullptr;
617}
618
620 SourceLocation NameLoc,
621 bool IsTemplateTypeArg) {
622 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
623
624 NestedNameSpecifier *NNS = nullptr;
625 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
626 // If we weren't able to parse a default template argument, delay lookup
627 // until instantiation time by making a non-dependent DependentTypeName. We
628 // pretend we saw a NestedNameSpecifier referring to the current scope, and
629 // lookup is retried.
630 // FIXME: This hurts our diagnostic quality, since we get errors like "no
631 // type named 'Foo' in 'current_namespace'" when the user didn't write any
632 // name specifiers.
634 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
635 } else if (const CXXRecordDecl *RD =
637 // Build a DependentNameType that will perform lookup into RD at
638 // instantiation time.
639 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
640 RD->getTypeForDecl());
641
642 // Diagnose that this identifier was undeclared, and retry the lookup during
643 // template instantiation.
644 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
645 << RD;
646 } else {
647 // This is not a situation that we should recover from.
648 return ParsedType();
649 }
650
651 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
652
653 // Build type location information. We synthesized the qualifier, so we have
654 // to build a fake NestedNameSpecifierLoc.
655 NestedNameSpecifierLocBuilder NNSLocBuilder;
656 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
657 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
658
659 TypeLocBuilder Builder;
660 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
661 DepTL.setNameLoc(NameLoc);
663 DepTL.setQualifierLoc(QualifierLoc);
664 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
665}
666
667/// isTagName() - This method is called *for error recovery purposes only*
668/// to determine if the specified name is a valid tag name ("struct foo"). If
669/// so, this returns the TST for the tag corresponding to it (TST_enum,
670/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
671/// cases in C where the user forgot to specify the tag.
673 // Do a tag name lookup in this scope.
674 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
675 LookupName(R, S, false);
678 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
679 switch (TD->getTagKind()) {
680 case TTK_Struct: return DeclSpec::TST_struct;
681 case TTK_Interface: return DeclSpec::TST_interface;
682 case TTK_Union: return DeclSpec::TST_union;
683 case TTK_Class: return DeclSpec::TST_class;
684 case TTK_Enum: return DeclSpec::TST_enum;
685 }
686 }
687
689}
690
691/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
692/// if a CXXScopeSpec's type is equal to the type of one of the base classes
693/// then downgrade the missing typename error to a warning.
694/// This is needed for MSVC compatibility; Example:
695/// @code
696/// template<class T> class A {
697/// public:
698/// typedef int TYPE;
699/// };
700/// template<class T> class B : public A<T> {
701/// public:
702/// A<T>::TYPE a; // no typename required because A<T> is a base class.
703/// };
704/// @endcode
706 if (CurContext->isRecord()) {
708 return true;
709
710 const Type *Ty = SS->getScopeRep()->getAsType();
711
713 for (const auto &Base : RD->bases())
714 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
715 return true;
716 return S->isFunctionPrototypeScope();
717 }
718 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
719}
720
722 SourceLocation IILoc,
723 Scope *S,
724 CXXScopeSpec *SS,
725 ParsedType &SuggestedType,
726 bool IsTemplateName) {
727 // Don't report typename errors for editor placeholders.
728 if (II->isEditorPlaceholder())
729 return;
730 // We don't have anything to suggest (yet).
731 SuggestedType = nullptr;
732
733 // There may have been a typo in the name of the type. Look up typo
734 // results, in case we have something that we can suggest.
735 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
736 /*AllowTemplates=*/IsTemplateName,
737 /*AllowNonTemplates=*/!IsTemplateName);
738 if (TypoCorrection Corrected =
740 CCC, CTK_ErrorRecovery)) {
741 // FIXME: Support error recovery for the template-name case.
742 bool CanRecover = !IsTemplateName;
743 if (Corrected.isKeyword()) {
744 // We corrected to a keyword.
745 diagnoseTypo(Corrected,
746 PDiag(IsTemplateName ? diag::err_no_template_suggest
747 : diag::err_unknown_typename_suggest)
748 << II);
749 II = Corrected.getCorrectionAsIdentifierInfo();
750 } else {
751 // We found a similarly-named type or interface; suggest that.
752 if (!SS || !SS->isSet()) {
753 diagnoseTypo(Corrected,
754 PDiag(IsTemplateName ? diag::err_no_template_suggest
755 : diag::err_unknown_typename_suggest)
756 << II, CanRecover);
757 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
758 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
759 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
760 II->getName().equals(CorrectedStr);
761 diagnoseTypo(Corrected,
762 PDiag(IsTemplateName
763 ? diag::err_no_member_template_suggest
764 : diag::err_unknown_nested_typename_suggest)
765 << II << DC << DroppedSpecifier << SS->getRange(),
766 CanRecover);
767 } else {
768 llvm_unreachable("could not have corrected a typo here");
769 }
770
771 if (!CanRecover)
772 return;
773
774 CXXScopeSpec tmpSS;
775 if (Corrected.getCorrectionSpecifier())
776 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
777 SourceRange(IILoc));
778 // FIXME: Support class template argument deduction here.
779 SuggestedType =
780 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
781 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
782 /*IsCtorOrDtorName=*/false,
783 /*WantNontrivialTypeSourceInfo=*/true);
784 }
785 return;
786 }
787
788 if (getLangOpts().CPlusPlus && !IsTemplateName) {
789 // See if II is a class template that the user forgot to pass arguments to.
790 UnqualifiedId Name;
791 Name.setIdentifier(II, IILoc);
792 CXXScopeSpec EmptySS;
793 TemplateTy TemplateResult;
794 bool MemberOfUnknownSpecialization;
795 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
796 Name, nullptr, true, TemplateResult,
797 MemberOfUnknownSpecialization) == TNK_Type_template) {
798 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
799 return;
800 }
801 }
802
803 // FIXME: Should we move the logic that tries to recover from a missing tag
804 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
805
806 if (!SS || (!SS->isSet() && !SS->isInvalid()))
807 Diag(IILoc, IsTemplateName ? diag::err_no_template
808 : diag::err_unknown_typename)
809 << II;
810 else if (DeclContext *DC = computeDeclContext(*SS, false))
811 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
812 : diag::err_typename_nested_not_found)
813 << II << DC << SS->getRange();
814 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
815 SuggestedType =
816 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
817 } else if (isDependentScopeSpecifier(*SS)) {
818 unsigned DiagID = diag::err_typename_missing;
819 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
820 DiagID = diag::ext_typename_missing;
821
822 Diag(SS->getRange().getBegin(), DiagID)
823 << SS->getScopeRep() << II->getName()
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
826 SuggestedType = ActOnTypenameType(S, SourceLocation(),
827 *SS, *II, IILoc).get();
828 } else {
829 assert(SS && SS->isInvalid() &&
830 "Invalid scope specifier has already been diagnosed");
831 }
832}
833
834/// Determine whether the given result set contains either a type name
835/// or
836static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
837 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
838 NextToken.is(tok::less);
839
840 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
841 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
842 return true;
843
844 if (CheckTemplate && isa<TemplateDecl>(*I))
845 return true;
846 }
847
848 return false;
849}
850
852 Scope *S, CXXScopeSpec &SS,
853 IdentifierInfo *&Name,
854 SourceLocation NameLoc) {
855 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
856 SemaRef.LookupParsedName(R, S, &SS);
857 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
858 StringRef FixItTagName;
859 switch (Tag->getTagKind()) {
860 case TTK_Class:
861 FixItTagName = "class ";
862 break;
863
864 case TTK_Enum:
865 FixItTagName = "enum ";
866 break;
867
868 case TTK_Struct:
869 FixItTagName = "struct ";
870 break;
871
872 case TTK_Interface:
873 FixItTagName = "__interface ";
874 break;
875
876 case TTK_Union:
877 FixItTagName = "union ";
878 break;
879 }
880
881 StringRef TagName = FixItTagName.drop_back();
882 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
883 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
884 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
885
886 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
887 I != IEnd; ++I)
888 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
889 << Name << TagName;
890
891 // Replace lookup results with just the tag decl.
893 SemaRef.LookupParsedName(Result, S, &SS);
894 return true;
895 }
896
897 return false;
898}
899
901 IdentifierInfo *&Name,
902 SourceLocation NameLoc,
903 const Token &NextToken,
905 DeclarationNameInfo NameInfo(Name, NameLoc);
906 ObjCMethodDecl *CurMethod = getCurMethodDecl();
907
908 assert(NextToken.isNot(tok::coloncolon) &&
909 "parse nested name specifiers before calling ClassifyName");
910 if (getLangOpts().CPlusPlus && SS.isSet() &&
911 isCurrentClassName(*Name, S, &SS)) {
912 // Per [class.qual]p2, this names the constructors of SS, not the
913 // injected-class-name. We don't have a classification for that.
914 // There's not much point caching this result, since the parser
915 // will reject it later.
917 }
918
919 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
920 LookupParsedName(Result, S, &SS, !CurMethod);
921
922 if (SS.isInvalid())
924
925 // For unqualified lookup in a class template in MSVC mode, look into
926 // dependent base classes where the primary class template is known.
927 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
928 if (ParsedType TypeInBase =
929 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
930 return TypeInBase;
931 }
932
933 // Perform lookup for Objective-C instance variables (including automatically
934 // synthesized instance variables), if we're in an Objective-C method.
935 // FIXME: This lookup really, really needs to be folded in to the normal
936 // unqualified lookup mechanism.
937 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
939 if (Ivar.isInvalid())
941 if (Ivar.isUsable())
942 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
943
944 // We defer builtin creation until after ivar lookup inside ObjC methods.
945 if (Result.empty())
947 }
948
949 bool SecondTry = false;
950 bool IsFilteredTemplateName = false;
951
952Corrected:
953 switch (Result.getResultKind()) {
955 // If an unqualified-id is followed by a '(', then we have a function
956 // call.
957 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
958 // In C++, this is an ADL-only call.
959 // FIXME: Reference?
962
963 // C90 6.3.2.2:
964 // If the expression that precedes the parenthesized argument list in a
965 // function call consists solely of an identifier, and if no
966 // declaration is visible for this identifier, the identifier is
967 // implicitly declared exactly as if, in the innermost block containing
968 // the function call, the declaration
969 //
970 // extern int identifier ();
971 //
972 // appeared.
973 //
974 // We also allow this in C99 as an extension. However, this is not
975 // allowed in all language modes as functions without prototypes may not
976 // be supported.
977 if (getLangOpts().implicitFunctionsAllowed()) {
978 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
980 }
981 }
982
983 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
984 // In C++20 onwards, this could be an ADL-only call to a function
985 // template, and we're required to assume that this is a template name.
986 //
987 // FIXME: Find a way to still do typo correction in this case.
988 TemplateName Template =
991 }
992
993 // In C, we first see whether there is a tag type by the same name, in
994 // which case it's likely that the user just forgot to write "enum",
995 // "struct", or "union".
996 if (!getLangOpts().CPlusPlus && !SecondTry &&
997 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
998 break;
999 }
1000
1001 // Perform typo correction to determine if there is another name that is
1002 // close to this name.
1003 if (!SecondTry && CCC) {
1004 SecondTry = true;
1005 if (TypoCorrection Corrected =
1006 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1007 &SS, *CCC, CTK_ErrorRecovery)) {
1008 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1009 unsigned QualifiedDiag = diag::err_no_member_suggest;
1010
1011 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1012 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1013 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1014 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1015 UnqualifiedDiag = diag::err_no_template_suggest;
1016 QualifiedDiag = diag::err_no_member_template_suggest;
1017 } else if (UnderlyingFirstDecl &&
1018 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1019 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1020 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1021 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1022 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1023 }
1024
1025 if (SS.isEmpty()) {
1026 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1027 } else {// FIXME: is this even reachable? Test it.
1028 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1029 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1030 Name->getName().equals(CorrectedStr);
1031 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1032 << Name << computeDeclContext(SS, false)
1033 << DroppedSpecifier << SS.getRange());
1034 }
1035
1036 // Update the name, so that the caller has the new name.
1037 Name = Corrected.getCorrectionAsIdentifierInfo();
1038
1039 // Typo correction corrected to a keyword.
1040 if (Corrected.isKeyword())
1041 return Name;
1042
1043 // Also update the LookupResult...
1044 // FIXME: This should probably go away at some point
1045 Result.clear();
1046 Result.setLookupName(Corrected.getCorrection());
1047 if (FirstDecl)
1048 Result.addDecl(FirstDecl);
1049
1050 // If we found an Objective-C instance variable, let
1051 // LookupInObjCMethod build the appropriate expression to
1052 // reference the ivar.
1053 // FIXME: This is a gross hack.
1054 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1055 DeclResult R =
1056 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1057 if (R.isInvalid())
1059 if (R.isUsable())
1060 return NameClassification::NonType(Ivar);
1061 }
1062
1063 goto Corrected;
1064 }
1065 }
1066
1067 // We failed to correct; just fall through and let the parser deal with it.
1068 Result.suppressDiagnostics();
1070
1072 // We performed name lookup into the current instantiation, and there were
1073 // dependent bases, so we treat this result the same way as any other
1074 // dependent nested-name-specifier.
1075
1076 // C++ [temp.res]p2:
1077 // A name used in a template declaration or definition and that is
1078 // dependent on a template-parameter is assumed not to name a type
1079 // unless the applicable name lookup finds a type name or the name is
1080 // qualified by the keyword typename.
1081 //
1082 // FIXME: If the next token is '<', we might want to ask the parser to
1083 // perform some heroics to see if we actually have a
1084 // template-argument-list, which would indicate a missing 'template'
1085 // keyword here.
1087 }
1088
1092 break;
1093
1095 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1096 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1097 /*AllowDependent=*/false)) {
1098 // C++ [temp.local]p3:
1099 // A lookup that finds an injected-class-name (10.2) can result in an
1100 // ambiguity in certain cases (for example, if it is found in more than
1101 // one base class). If all of the injected-class-names that are found
1102 // refer to specializations of the same class template, and if the name
1103 // is followed by a template-argument-list, the reference refers to the
1104 // class template itself and not a specialization thereof, and is not
1105 // ambiguous.
1106 //
1107 // This filtering can make an ambiguous result into an unambiguous one,
1108 // so try again after filtering out template names.
1110 if (!Result.isAmbiguous()) {
1111 IsFilteredTemplateName = true;
1112 break;
1113 }
1114 }
1115
1116 // Diagnose the ambiguity and return an error.
1118 }
1119
1120 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1121 (IsFilteredTemplateName ||
1123 Result, /*AllowFunctionTemplates=*/true,
1124 /*AllowDependent=*/false,
1125 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1127 // C++ [temp.names]p3:
1128 // After name lookup (3.4) finds that a name is a template-name or that
1129 // an operator-function-id or a literal- operator-id refers to a set of
1130 // overloaded functions any member of which is a function template if
1131 // this is followed by a <, the < is always taken as the delimiter of a
1132 // template-argument-list and never as the less-than operator.
1133 // C++2a [temp.names]p2:
1134 // A name is also considered to refer to a template if it is an
1135 // unqualified-id followed by a < and name lookup finds either one
1136 // or more functions or finds nothing.
1137 if (!IsFilteredTemplateName)
1139
1140 bool IsFunctionTemplate;
1141 bool IsVarTemplate;
1142 TemplateName Template;
1143 if (Result.end() - Result.begin() > 1) {
1144 IsFunctionTemplate = true;
1145 Template = Context.getOverloadedTemplateName(Result.begin(),
1146 Result.end());
1147 } else if (!Result.empty()) {
1149 *Result.begin(), /*AllowFunctionTemplates=*/true,
1150 /*AllowDependent=*/false));
1151 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1152 IsVarTemplate = isa<VarTemplateDecl>(TD);
1153
1154 UsingShadowDecl *FoundUsingShadow =
1155 dyn_cast<UsingShadowDecl>(*Result.begin());
1156 assert(!FoundUsingShadow ||
1157 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1158 Template =
1159 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1160 if (SS.isNotEmpty())
1162 /*TemplateKeyword=*/false,
1163 Template);
1164 } else {
1165 // All results were non-template functions. This is a function template
1166 // name.
1167 IsFunctionTemplate = true;
1168 Template = Context.getAssumedTemplateName(NameInfo.getName());
1169 }
1170
1171 if (IsFunctionTemplate) {
1172 // Function templates always go through overload resolution, at which
1173 // point we'll perform the various checks (e.g., accessibility) we need
1174 // to based on which function we selected.
1175 Result.suppressDiagnostics();
1176
1177 return NameClassification::FunctionTemplate(Template);
1178 }
1179
1180 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1182 }
1183
1184 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1186 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1187 T = Context.getUsingType(USD, T);
1188 return buildNamedType(*this, &SS, T, NameLoc);
1189 };
1190
1192 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1193 DiagnoseUseOfDecl(Type, NameLoc);
1194 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1195 return BuildTypeFor(Type, *Result.begin());
1196 }
1197
1198 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1199 if (!Class) {
1200 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1201 if (ObjCCompatibleAliasDecl *Alias =
1202 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1203 Class = Alias->getClassInterface();
1204 }
1205
1206 if (Class) {
1207 DiagnoseUseOfDecl(Class, NameLoc);
1208
1209 if (NextToken.is(tok::period)) {
1210 // Interface. <something> is parsed as a property reference expression.
1211 // Just return "unknown" as a fall-through for now.
1212 Result.suppressDiagnostics();
1214 }
1215
1217 return ParsedType::make(T);
1218 }
1219
1220 if (isa<ConceptDecl>(FirstDecl))
1222 TemplateName(cast<TemplateDecl>(FirstDecl)));
1223
1224 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1225 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1227 }
1228
1229 // We can have a type template here if we're classifying a template argument.
1230 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1231 !isa<VarTemplateDecl>(FirstDecl))
1233 TemplateName(cast<TemplateDecl>(FirstDecl)));
1234
1235 // Check for a tag type hidden by a non-type decl in a few cases where it
1236 // seems likely a type is wanted instead of the non-type that was found.
1237 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1238 if ((NextToken.is(tok::identifier) ||
1239 (NextIsOp &&
1240 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1241 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1242 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1243 DiagnoseUseOfDecl(Type, NameLoc);
1244 return BuildTypeFor(Type, *Result.begin());
1245 }
1246
1247 // If we already know which single declaration is referenced, just annotate
1248 // that declaration directly. Defer resolving even non-overloaded class
1249 // member accesses, as we need to defer certain access checks until we know
1250 // the context.
1251 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1252 if (Result.isSingleResult() && !ADL &&
1253 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1254 return NameClassification::NonType(Result.getRepresentativeDecl());
1255
1256 // Otherwise, this is an overload set that we will need to resolve later.
1257 Result.suppressDiagnostics();
1259 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1260 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1261 Result.begin(), Result.end()));
1262}
1263
1266 SourceLocation NameLoc) {
1267 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1268 CXXScopeSpec SS;
1269 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1270 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1271}
1272
1275 IdentifierInfo *Name,
1276 SourceLocation NameLoc,
1277 bool IsAddressOfOperand) {
1278 DeclarationNameInfo NameInfo(Name, NameLoc);
1279 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1280 NameInfo, IsAddressOfOperand,
1281 /*TemplateArgs=*/nullptr);
1282}
1283
1285 NamedDecl *Found,
1286 SourceLocation NameLoc,
1287 const Token &NextToken) {
1288 if (getCurMethodDecl() && SS.isEmpty())
1289 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1290 return BuildIvarRefExpr(S, NameLoc, Ivar);
1291
1292 // Reconstruct the lookup result.
1293 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1294 Result.addDecl(Found);
1295 Result.resolveKind();
1296
1297 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1298 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1299}
1300
1302 // For an implicit class member access, transform the result into a member
1303 // access expression if necessary.
1304 auto *ULE = cast<UnresolvedLookupExpr>(E);
1305 if ((*ULE->decls_begin())->isCXXClassMember()) {
1306 CXXScopeSpec SS;
1307 SS.Adopt(ULE->getQualifierLoc());
1308
1309 // Reconstruct the lookup result.
1310 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1312 Result.setNamingClass(ULE->getNamingClass());
1313 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1314 Result.addDecl(*I, I.getAccess());
1315 Result.resolveKind();
1317 nullptr, S);
1318 }
1319
1320 // Otherwise, this is already in the form we needed, and no further checks
1321 // are necessary.
1322 return ULE;
1323}
1324
1327 auto *TD = Name.getAsTemplateDecl();
1328 if (!TD)
1330 if (isa<ClassTemplateDecl>(TD))
1332 if (isa<FunctionTemplateDecl>(TD))
1334 if (isa<VarTemplateDecl>(TD))
1336 if (isa<TypeAliasTemplateDecl>(TD))
1338 if (isa<TemplateTemplateParmDecl>(TD))
1340 if (isa<ConceptDecl>(TD))
1343}
1344
1346 assert(DC->getLexicalParent() == CurContext &&
1347 "The next DeclContext should be lexically contained in the current one.");
1348 CurContext = DC;
1349 S->setEntity(DC);
1350}
1351
1353 assert(CurContext && "DeclContext imbalance!");
1354
1356 assert(CurContext && "Popped translation unit!");
1357}
1358
1360 Decl *D) {
1361 // Unlike PushDeclContext, the context to which we return is not necessarily
1362 // the containing DC of TD, because the new context will be some pre-existing
1363 // TagDecl definition instead of a fresh one.
1364 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1365 CurContext = cast<TagDecl>(D)->getDefinition();
1366 assert(CurContext && "skipping definition of undefined tag");
1367 // Start lookups from the parent of the current context; we don't want to look
1368 // into the pre-existing complete definition.
1369 S->setEntity(CurContext->getLookupParent());
1370 return Result;
1371}
1372
1376
1377/// EnterDeclaratorContext - Used when we must lookup names in the context
1378/// of a declarator's nested name specifier.
1379///
1381 // C++0x [basic.lookup.unqual]p13:
1382 // A name used in the definition of a static data member of class
1383 // X (after the qualified-id of the static member) is looked up as
1384 // if the name was used in a member function of X.
1385 // C++0x [basic.lookup.unqual]p14:
1386 // If a variable member of a namespace is defined outside of the
1387 // scope of its namespace then any name used in the definition of
1388 // the variable member (after the declarator-id) is looked up as
1389 // if the definition of the variable member occurred in its
1390 // namespace.
1391 // Both of these imply that we should push a scope whose context
1392 // is the semantic context of the declaration. We can't use
1393 // PushDeclContext here because that context is not necessarily
1394 // lexically contained in the current context. Fortunately,
1395 // the containing scope should have the appropriate information.
1396
1397 assert(!S->getEntity() && "scope already has entity");
1398
1399#ifndef NDEBUG
1400 Scope *Ancestor = S->getParent();
1401 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1402 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1403#endif
1404
1405 CurContext = DC;
1406 S->setEntity(DC);
1407
1408 if (S->getParent()->isTemplateParamScope()) {
1409 // Also set the corresponding entities for all immediately-enclosing
1410 // template parameter scopes.
1411 EnterTemplatedContext(S->getParent(), DC);
1412 }
1413}
1414
1416 assert(S->getEntity() == CurContext && "Context imbalance!");
1417
1418 // Switch back to the lexical context. The safety of this is
1419 // enforced by an assert in EnterDeclaratorContext.
1420 Scope *Ancestor = S->getParent();
1421 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1422 CurContext = Ancestor->getEntity();
1423
1424 // We don't need to do anything with the scope, which is going to
1425 // disappear.
1426}
1427
1429 assert(S->isTemplateParamScope() &&
1430 "expected to be initializing a template parameter scope");
1431
1432 // C++20 [temp.local]p7:
1433 // In the definition of a member of a class template that appears outside
1434 // of the class template definition, the name of a member of the class
1435 // template hides the name of a template-parameter of any enclosing class
1436 // templates (but not a template-parameter of the member if the member is a
1437 // class or function template).
1438 // C++20 [temp.local]p9:
1439 // In the definition of a class template or in the definition of a member
1440 // of such a template that appears outside of the template definition, for
1441 // each non-dependent base class (13.8.2.1), if the name of the base class
1442 // or the name of a member of the base class is the same as the name of a
1443 // template-parameter, the base class name or member name hides the
1444 // template-parameter name (6.4.10).
1445 //
1446 // This means that a template parameter scope should be searched immediately
1447 // after searching the DeclContext for which it is a template parameter
1448 // scope. For example, for
1449 // template<typename T> template<typename U> template<typename V>
1450 // void N::A<T>::B<U>::f(...)
1451 // we search V then B<U> (and base classes) then U then A<T> (and base
1452 // classes) then T then N then ::.
1453 unsigned ScopeDepth = getTemplateDepth(S);
1454 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1455 DeclContext *SearchDCAfterScope = DC;
1456 for (; DC; DC = DC->getLookupParent()) {
1457 if (const TemplateParameterList *TPL =
1458 cast<Decl>(DC)->getDescribedTemplateParams()) {
1459 unsigned DCDepth = TPL->getDepth() + 1;
1460 if (DCDepth > ScopeDepth)
1461 continue;
1462 if (ScopeDepth == DCDepth)
1463 SearchDCAfterScope = DC = DC->getLookupParent();
1464 break;
1465 }
1466 }
1467 S->setLookupEntity(SearchDCAfterScope);
1468 }
1469}
1470
1472 // We assume that the caller has already called
1473 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1474 FunctionDecl *FD = D->getAsFunction();
1475 if (!FD)
1476 return;
1477
1478 // Same implementation as PushDeclContext, but enters the context
1479 // from the lexical parent, rather than the top-level class.
1480 assert(CurContext == FD->getLexicalParent() &&
1481 "The next DeclContext should be lexically contained in the current one.");
1482 CurContext = FD;
1483 S->setEntity(CurContext);
1484
1485 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1486 ParmVarDecl *Param = FD->getParamDecl(P);
1487 // If the parameter has an identifier, then add it to the scope
1488 if (Param->getIdentifier()) {
1489 S->AddDecl(Param);
1490 IdResolver.AddDecl(Param);
1491 }
1492 }
1493}
1494
1496 // Same implementation as PopDeclContext, but returns to the lexical parent,
1497 // rather than the top-level class.
1498 assert(CurContext && "DeclContext imbalance!");
1500 assert(CurContext && "Popped translation unit!");
1501}
1502
1503/// Determine whether overloading is allowed for a new function
1504/// declaration considering prior declarations of the same name.
1505///
1506/// This routine determines whether overloading is possible, not
1507/// whether a new declaration actually overloads a previous one.
1508/// It will return true in C++ (where overloads are alway permitted)
1509/// or, as a C extension, when either the new declaration or a
1510/// previous one is declared with the 'overloadable' attribute.
1512 ASTContext &Context,
1513 const FunctionDecl *New) {
1514 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1515 return true;
1516
1517 // Multiversion function declarations are not overloads in the
1518 // usual sense of that term, but lookup will report that an
1519 // overload set was found if more than one multiversion function
1520 // declaration is present for the same name. It is therefore
1521 // inadequate to assume that some prior declaration(s) had
1522 // the overloadable attribute; checking is required. Since one
1523 // declaration is permitted to omit the attribute, it is necessary
1524 // to check at least two; hence the 'any_of' check below. Note that
1525 // the overloadable attribute is implicitly added to declarations
1526 // that were required to have it but did not.
1527 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1528 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1529 return ND->hasAttr<OverloadableAttr>();
1530 });
1531 } else if (Previous.getResultKind() == LookupResult::Found)
1532 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1533
1534 return false;
1535}
1536
1537/// Add this decl to the scope shadowed decl chains.
1538void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1539 // Move up the scope chain until we find the nearest enclosing
1540 // non-transparent context. The declaration will be introduced into this
1541 // scope.
1542 while (S->getEntity() && S->getEntity()->isTransparentContext())
1543 S = S->getParent();
1544
1545 // Add scoped declarations into their context, so that they can be
1546 // found later. Declarations without a context won't be inserted
1547 // into any context.
1548 if (AddToContext)
1549 CurContext->addDecl(D);
1550
1551 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1552 // are function-local declarations.
1553 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1554 return;
1555
1556 // Template instantiations should also not be pushed into scope.
1557 if (isa<FunctionDecl>(D) &&
1558 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1559 return;
1560
1561 // If this replaces anything in the current scope,
1563 IEnd = IdResolver.end();
1564 for (; I != IEnd; ++I) {
1565 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1566 S->RemoveDecl(*I);
1568
1569 // Should only need to replace one decl.
1570 break;
1571 }
1572 }
1573
1574 S->AddDecl(D);
1575
1576 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1577 // Implicitly-generated labels may end up getting generated in an order that
1578 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1579 // the label at the appropriate place in the identifier chain.
1580 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1581 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1582 if (IDC == CurContext) {
1583 if (!S->isDeclScope(*I))
1584 continue;
1585 } else if (IDC->Encloses(CurContext))
1586 break;
1587 }
1588
1590 } else {
1592 }
1594}
1595
1597 bool AllowInlineNamespace) const {
1598 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1599}
1600
1602 DeclContext *TargetDC = DC->getPrimaryContext();
1603 do {
1604 if (DeclContext *ScopeDC = S->getEntity())
1605 if (ScopeDC->getPrimaryContext() == TargetDC)
1606 return S;
1607 } while ((S = S->getParent()));
1608
1609 return nullptr;
1610}
1611
1613 DeclContext*,
1614 ASTContext&);
1615
1616/// Filters out lookup results that don't fall within the given scope
1617/// as determined by isDeclInScope.
1619 bool ConsiderLinkage,
1620 bool AllowInlineNamespace) {
1622 while (F.hasNext()) {
1623 NamedDecl *D = F.next();
1624
1625 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1626 continue;
1627
1628 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1629 continue;
1630
1631 F.erase();
1632 }
1633
1634 F.done();
1635}
1636
1637/// We've determined that \p New is a redeclaration of \p Old. Check that they
1638/// have compatible owning modules.
1640 // [module.interface]p7:
1641 // A declaration is attached to a module as follows:
1642 // - If the declaration is a non-dependent friend declaration that nominates a
1643 // function with a declarator-id that is a qualified-id or template-id or that
1644 // nominates a class other than with an elaborated-type-specifier with neither
1645 // a nested-name-specifier nor a simple-template-id, it is attached to the
1646 // module to which the friend is attached ([basic.link]).
1647 if (New->getFriendObjectKind() &&
1651 return false;
1652 }
1653
1654 Module *NewM = New->getOwningModule();
1655 Module *OldM = Old->getOwningModule();
1656
1657 if (NewM && NewM->isPrivateModule())
1658 NewM = NewM->Parent;
1659 if (OldM && OldM->isPrivateModule())
1660 OldM = OldM->Parent;
1661
1662 if (NewM == OldM)
1663 return false;
1664
1665 if (NewM && OldM) {
1666 // A module implementation unit has visibility of the decls in its
1667 // implicitly imported interface.
1668 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1669 return false;
1670
1671 // Partitions are part of the module, but a partition could import another
1672 // module, so verify that the PMIs agree.
1673 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1676 return false;
1677 }
1678
1679 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1680 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1681 if (NewIsModuleInterface || OldIsModuleInterface) {
1682 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1683 // if a declaration of D [...] appears in the purview of a module, all
1684 // other such declarations shall appear in the purview of the same module
1685 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1686 << New
1687 << NewIsModuleInterface
1688 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1689 << OldIsModuleInterface
1690 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1691 Diag(Old->getLocation(), diag::note_previous_declaration);
1692 New->setInvalidDecl();
1693 return true;
1694 }
1695
1696 return false;
1697}
1698
1699// [module.interface]p6:
1700// A redeclaration of an entity X is implicitly exported if X was introduced by
1701// an exported declaration; otherwise it shall not be exported.
1703 // [module.interface]p1:
1704 // An export-declaration shall inhabit a namespace scope.
1705 //
1706 // So it is meaningless to talk about redeclaration which is not at namespace
1707 // scope.
1708 if (!New->getLexicalDeclContext()
1710 ->isFileContext() ||
1711 !Old->getLexicalDeclContext()
1713 ->isFileContext())
1714 return false;
1715
1716 bool IsNewExported = New->isInExportDeclContext();
1717 bool IsOldExported = Old->isInExportDeclContext();
1718
1719 // It should be irrevelant if both of them are not exported.
1720 if (!IsNewExported && !IsOldExported)
1721 return false;
1722
1723 if (IsOldExported)
1724 return false;
1725
1726 assert(IsNewExported);
1727
1728 auto Lk = Old->getFormalLinkage();
1729 int S = 0;
1730 if (Lk == Linkage::InternalLinkage)
1731 S = 1;
1732 else if (Lk == Linkage::ModuleLinkage)
1733 S = 2;
1734 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1735 Diag(Old->getLocation(), diag::note_previous_declaration);
1736 return true;
1737}
1738
1739// A wrapper function for checking the semantic restrictions of
1740// a redeclaration within a module.
1743 return true;
1744
1745 if (CheckRedeclarationExported(New, Old))
1746 return true;
1747
1748 return false;
1749}
1750
1751// Check the redefinition in C++20 Modules.
1752//
1753// [basic.def.odr]p14:
1754// For any definable item D with definitions in multiple translation units,
1755// - if D is a non-inline non-templated function or variable, or
1756// - if the definitions in different translation units do not satisfy the
1757// following requirements,
1758// the program is ill-formed; a diagnostic is required only if the definable
1759// item is attached to a named module and a prior definition is reachable at
1760// the point where a later definition occurs.
1761// - Each such definition shall not be attached to a named module
1762// ([module.unit]).
1763// - Each such definition shall consist of the same sequence of tokens, ...
1764// ...
1765//
1766// Return true if the redefinition is not allowed. Return false otherwise.
1768 const NamedDecl *Old) const {
1769 assert(getASTContext().isSameEntity(New, Old) &&
1770 "New and Old are not the same definition, we should diagnostic it "
1771 "immediately instead of checking it.");
1772 assert(const_cast<Sema *>(this)->isReachable(New) &&
1773 const_cast<Sema *>(this)->isReachable(Old) &&
1774 "We shouldn't see unreachable definitions here.");
1775
1776 Module *NewM = New->getOwningModule();
1777 Module *OldM = Old->getOwningModule();
1778
1779 // We only checks for named modules here. The header like modules is skipped.
1780 // FIXME: This is not right if we import the header like modules in the module
1781 // purview.
1782 //
1783 // For example, assuming "header.h" provides definition for `D`.
1784 // ```C++
1785 // //--- M.cppm
1786 // export module M;
1787 // import "header.h"; // or #include "header.h" but import it by clang modules
1788 // actually.
1789 //
1790 // //--- Use.cpp
1791 // import M;
1792 // import "header.h"; // or uses clang modules.
1793 // ```
1794 //
1795 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1796 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1797 // reject it. But the current implementation couldn't detect the case since we
1798 // don't record the information about the importee modules.
1799 //
1800 // But this might not be painful in practice. Since the design of C++20 Named
1801 // Modules suggests us to use headers in global module fragment instead of
1802 // module purview.
1803 if (NewM && NewM->isHeaderLikeModule())
1804 NewM = nullptr;
1805 if (OldM && OldM->isHeaderLikeModule())
1806 OldM = nullptr;
1807
1808 if (!NewM && !OldM)
1809 return true;
1810
1811 // [basic.def.odr]p14.3
1812 // Each such definition shall not be attached to a named module
1813 // ([module.unit]).
1814 if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
1815 return true;
1816
1817 // Then New and Old lives in the same TU if their share one same module unit.
1818 if (NewM)
1819 NewM = NewM->getTopLevelModule();
1820 if (OldM)
1821 OldM = OldM->getTopLevelModule();
1822 return OldM == NewM;
1823}
1824
1826 if (D->getDeclContext()->isFileContext())
1827 return false;
1828
1829 return isa<UsingShadowDecl>(D) ||
1832}
1833
1834/// Removes using shadow declarations not at class scope from the lookup
1835/// results.
1838 while (F.hasNext())
1840 F.erase();
1841
1842 F.done();
1843}
1844
1845/// Check for this common pattern:
1846/// @code
1847/// class S {
1848/// S(const S&); // DO NOT IMPLEMENT
1849/// void operator=(const S&); // DO NOT IMPLEMENT
1850/// };
1851/// @endcode
1853 // FIXME: Should check for private access too but access is set after we get
1854 // the decl here.
1856 return false;
1857
1858 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1859 return CD->isCopyConstructor();
1860 return D->isCopyAssignmentOperator();
1861}
1862
1863// We need this to handle
1864//
1865// typedef struct {
1866// void *foo() { return 0; }
1867// } A;
1868//
1869// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1870// for example. If 'A', foo will have external linkage. If we have '*A',
1871// foo will have no linkage. Since we can't know until we get to the end
1872// of the typedef, this function finds out if D might have non-external linkage.
1873// Callers should verify at the end of the TU if it D has external linkage or
1874// not.
1875bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1876 const DeclContext *DC = D->getDeclContext();
1877 while (!DC->isTranslationUnit()) {
1878 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1879 if (!RD->hasNameForLinkage())
1880 return true;
1881 }
1882 DC = DC->getParent();
1883 }
1884
1885 return !D->isExternallyVisible();
1886}
1887
1888// FIXME: This needs to be refactored; some other isInMainFile users want
1889// these semantics.
1890static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1892 return false;
1893 return S.SourceMgr.isInMainFile(Loc);
1894}
1895
1897 assert(D);
1898
1899 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1900 return false;
1901
1902 // Ignore all entities declared within templates, and out-of-line definitions
1903 // of members of class templates.
1904 if (D->getDeclContext()->isDependentContext() ||
1906 return false;
1907
1908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1909 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1910 return false;
1911 // A non-out-of-line declaration of a member specialization was implicitly
1912 // instantiated; it's the out-of-line declaration that we're interested in.
1913 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1914 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1915 return false;
1916
1917 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1918 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1919 return false;
1920 } else {
1921 // 'static inline' functions are defined in headers; don't warn.
1922 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1923 return false;
1924 }
1925
1926 if (FD->doesThisDeclarationHaveABody() &&
1928 return false;
1929 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1930 // Constants and utility variables are defined in headers with internal
1931 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1932 // like "inline".)
1933 if (!isMainFileLoc(*this, VD->getLocation()))
1934 return false;
1935
1936 if (Context.DeclMustBeEmitted(VD))
1937 return false;
1938
1939 if (VD->isStaticDataMember() &&
1940 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1941 return false;
1942 if (VD->isStaticDataMember() &&
1943 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1944 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1945 return false;
1946
1947 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1948 return false;
1949 } else {
1950 return false;
1951 }
1952
1953 // Only warn for unused decls internal to the translation unit.
1954 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1955 // for inline functions defined in the main source file, for instance.
1956 return mightHaveNonExternalLinkage(D);
1957}
1958
1960 if (!D)
1961 return;
1962
1963 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1964 const FunctionDecl *First = FD->getFirstDecl();
1966 return; // First should already be in the vector.
1967 }
1968
1969 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1970 const VarDecl *First = VD->getFirstDecl();
1972 return; // First should already be in the vector.
1973 }
1974
1977}
1978
1980 if (D->isInvalidDecl())
1981 return false;
1982
1983 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1984 // For a decomposition declaration, warn if none of the bindings are
1985 // referenced, instead of if the variable itself is referenced (which
1986 // it is, by the bindings' expressions).
1987 for (auto *BD : DD->bindings())
1988 if (BD->isReferenced())
1989 return false;
1990 } else if (!D->getDeclName()) {
1991 return false;
1992 } else if (D->isReferenced() || D->isUsed()) {
1993 return false;
1994 }
1995
1996 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1997 D->hasAttr<CleanupAttr>())
1998 return false;
1999
2000 if (isa<LabelDecl>(D))
2001 return true;
2002
2003 // Except for labels, we only care about unused decls that are local to
2004 // functions.
2005 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2006 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2007 // For dependent types, the diagnostic is deferred.
2008 WithinFunction =
2009 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2010 if (!WithinFunction)
2011 return false;
2012
2013 if (isa<TypedefNameDecl>(D))
2014 return true;
2015
2016 // White-list anything that isn't a local variable.
2017 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2018 return false;
2019
2020 // Types of valid local variables should be complete, so this should succeed.
2021 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2022
2023 const Expr *Init = VD->getInit();
2024 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
2025 Init = Cleanups->getSubExpr();
2026
2027 const auto *Ty = VD->getType().getTypePtr();
2028
2029 // Only look at the outermost level of typedef.
2030 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2031 // Allow anything marked with __attribute__((unused)).
2032 if (TT->getDecl()->hasAttr<UnusedAttr>())
2033 return false;
2034 }
2035
2036 // Warn for reference variables whose initializtion performs lifetime
2037 // extension.
2038 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
2039 if (MTE->getExtendingDecl()) {
2040 Ty = VD->getType().getNonReferenceType().getTypePtr();
2041 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2042 }
2043 }
2044
2045 // If we failed to complete the type for some reason, or if the type is
2046 // dependent, don't diagnose the variable.
2047 if (Ty->isIncompleteType() || Ty->isDependentType())
2048 return false;
2049
2050 // Look at the element type to ensure that the warning behaviour is
2051 // consistent for both scalars and arrays.
2052 Ty = Ty->getBaseElementTypeUnsafe();
2053
2054 if (const TagType *TT = Ty->getAs<TagType>()) {
2055 const TagDecl *Tag = TT->getDecl();
2056 if (Tag->hasAttr<UnusedAttr>())
2057 return false;
2058
2059 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2060 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2061 return false;
2062
2063 if (Init) {
2064 const CXXConstructExpr *Construct =
2065 dyn_cast<CXXConstructExpr>(Init);
2066 if (Construct && !Construct->isElidable()) {
2067 CXXConstructorDecl *CD = Construct->getConstructor();
2068 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2069 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2070 return false;
2071 }
2072
2073 // Suppress the warning if we don't know how this is constructed, and
2074 // it could possibly be non-trivial constructor.
2075 if (Init->isTypeDependent()) {
2076 for (const CXXConstructorDecl *Ctor : RD->ctors())
2077 if (!Ctor->isTrivial())
2078 return false;
2079 }
2080
2081 // Suppress the warning if the constructor is unresolved because
2082 // its arguments are dependent.
2083 if (isa<CXXUnresolvedConstructExpr>(Init))
2084 return false;
2085 }
2086 }
2087 }
2088
2089 // TODO: __attribute__((unused)) templates?
2090 }
2091
2092 return true;
2093}
2094
2096 FixItHint &Hint) {
2097 if (isa<LabelDecl>(D)) {
2099 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2100 /*SkipTrailingWhitespaceAndNewline=*/false);
2101 if (AfterColon.isInvalid())
2102 return;
2104 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2105 }
2106}
2107
2110 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2111}
2112
2114 DiagReceiverTy DiagReceiver) {
2115 if (D->getTypeForDecl()->isDependentType())
2116 return;
2117
2118 for (auto *TmpD : D->decls()) {
2119 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2120 DiagnoseUnusedDecl(T, DiagReceiver);
2121 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2122 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2123 }
2124}
2125
2128 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2129}
2130
2131/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2132/// unless they are marked attr(unused).
2135 return;
2136
2137 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2138 // typedefs can be referenced later on, so the diagnostics are emitted
2139 // at end-of-translation-unit.
2141 return;
2142 }
2143
2144 FixItHint Hint;
2146
2147 unsigned DiagID;
2148 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2149 DiagID = diag::warn_unused_exception_param;
2150 else if (isa<LabelDecl>(D))
2151 DiagID = diag::warn_unused_label;
2152 else
2153 DiagID = diag::warn_unused_variable;
2154
2155 SourceLocation DiagLoc = D->getLocation();
2156 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2157}
2158
2160 DiagReceiverTy DiagReceiver) {
2161 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2162 // it's not really unused.
2163 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2164 VD->hasAttr<CleanupAttr>())
2165 return;
2166
2167 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2168
2169 if (Ty->isReferenceType() || Ty->isDependentType())
2170 return;
2171
2172 if (const TagType *TT = Ty->getAs<TagType>()) {
2173 const TagDecl *Tag = TT->getDecl();
2174 if (Tag->hasAttr<UnusedAttr>())
2175 return;
2176 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2177 // mimic gcc's behavior.
2178 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2179 if (!RD->hasAttr<WarnUnusedAttr>())
2180 return;
2181 }
2182 }
2183
2184 // Don't warn about __block Objective-C pointer variables, as they might
2185 // be assigned in the block but not used elsewhere for the purpose of lifetime
2186 // extension.
2187 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2188 return;
2189
2190 // Don't warn about Objective-C pointer variables with precise lifetime
2191 // semantics; they can be used to ensure ARC releases the object at a known
2192 // time, which may mean assignment but no other references.
2193 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2194 return;
2195
2196 auto iter = RefsMinusAssignments.find(VD);
2197 if (iter == RefsMinusAssignments.end())
2198 return;
2199
2200 assert(iter->getSecond() >= 0 &&
2201 "Found a negative number of references to a VarDecl");
2202 if (iter->getSecond() != 0)
2203 return;
2204 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2205 : diag::warn_unused_but_set_variable;
2206 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2207}
2208
2210 Sema::DiagReceiverTy DiagReceiver) {
2211 // Verify that we have no forward references left. If so, there was a goto
2212 // or address of a label taken, but no definition of it. Label fwd
2213 // definitions are indicated with a null substmt which is also not a resolved
2214 // MS inline assembly label name.
2215 bool Diagnose = false;
2216 if (L->isMSAsmLabel())
2217 Diagnose = !L->isResolvedMSAsmLabel();
2218 else
2219 Diagnose = L->getStmt() == nullptr;
2220 if (Diagnose)
2221 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2222 << L);
2223}
2224
2226 S->applyNRVO();
2227
2228 if (S->decl_empty()) return;
2229 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2230 "Scope shouldn't contain decls!");
2231
2232 /// We visit the decls in non-deterministic order, but we want diagnostics
2233 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2234 /// and sort the diagnostics before emitting them, after we visited all decls.
2235 struct LocAndDiag {
2236 SourceLocation Loc;
2237 std::optional<SourceLocation> PreviousDeclLoc;
2239 };
2241 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2242 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2243 };
2244 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2245 SourceLocation PreviousDeclLoc,
2246 PartialDiagnostic PD) {
2247 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2248 };
2249
2250 for (auto *TmpD : S->decls()) {
2251 assert(TmpD && "This decl didn't get pushed??");
2252
2253 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2254 NamedDecl *D = cast<NamedDecl>(TmpD);
2255
2256 // Diagnose unused variables in this scope.
2257 if (!S->hasUnrecoverableErrorOccurred()) {
2258 DiagnoseUnusedDecl(D, addDiag);
2259 if (const auto *RD = dyn_cast<RecordDecl>(D))
2260 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2261 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2262 DiagnoseUnusedButSetDecl(VD, addDiag);
2263 RefsMinusAssignments.erase(VD);
2264 }
2265 }
2266
2267 if (!D->getDeclName()) continue;
2268
2269 // If this was a forward reference to a label, verify it was defined.
2270 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2271 CheckPoppedLabel(LD, *this, addDiag);
2272
2273 // Remove this name from our lexical scope, and warn on it if we haven't
2274 // already.
2276 auto ShadowI = ShadowingDecls.find(D);
2277 if (ShadowI != ShadowingDecls.end()) {
2278 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2279 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2280 PDiag(diag::warn_ctor_parm_shadows_field)
2281 << D << FD << FD->getParent());
2282 }
2283 ShadowingDecls.erase(ShadowI);
2284 }
2285 }
2286
2287 llvm::sort(DeclDiags,
2288 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2289 // The particular order for diagnostics is not important, as long
2290 // as the order is deterministic. Using the raw location is going
2291 // to generally be in source order unless there are macro
2292 // expansions involved.
2293 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2294 });
2295 for (const LocAndDiag &D : DeclDiags) {
2296 Diag(D.Loc, D.PD);
2297 if (D.PreviousDeclLoc)
2298 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2299 }
2300}
2301
2302/// Look for an Objective-C class in the translation unit.
2303///
2304/// \param Id The name of the Objective-C class we're looking for. If
2305/// typo-correction fixes this name, the Id will be updated
2306/// to the fixed name.
2307///
2308/// \param IdLoc The location of the name in the translation unit.
2309///
2310/// \param DoTypoCorrection If true, this routine will attempt typo correction
2311/// if there is no class with the given name.
2312///
2313/// \returns The declaration of the named Objective-C class, or NULL if the
2314/// class could not be found.
2316 SourceLocation IdLoc,
2317 bool DoTypoCorrection) {
2318 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2319 // creation from this context.
2321
2322 if (!IDecl && DoTypoCorrection) {
2323 // Perform typo correction at the given location, but only if we
2324 // find an Objective-C class name.
2326 if (TypoCorrection C =
2328 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2329 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2330 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2331 Id = IDecl->getIdentifier();
2332 }
2333 }
2334 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2335 // This routine must always return a class definition, if any.
2336 if (Def && Def->getDefinition())
2337 Def = Def->getDefinition();
2338 return Def;
2339}
2340
2341/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2342/// from S, where a non-field would be declared. This routine copes
2343/// with the difference between C and C++ scoping rules in structs and
2344/// unions. For example, the following code is well-formed in C but
2345/// ill-formed in C++:
2346/// @code
2347/// struct S6 {
2348/// enum { BAR } e;
2349/// };
2350///
2351/// void test_S6() {
2352/// struct S6 a;
2353/// a.e = BAR;
2354/// }
2355/// @endcode
2356/// For the declaration of BAR, this routine will return a different
2357/// scope. The scope S will be the scope of the unnamed enumeration
2358/// within S6. In C++, this routine will return the scope associated
2359/// with S6, because the enumeration's scope is a transparent
2360/// context but structures can contain non-field names. In C, this
2361/// routine will return the translation unit scope, since the
2362/// enumeration's scope is a transparent context and structures cannot
2363/// contain non-field names.
2365 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2366 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2367 (S->isClassScope() && !getLangOpts().CPlusPlus))
2368 S = S->getParent();
2369 return S;
2370}
2371
2372static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2374 switch (Error) {
2376 return "";
2378 return BuiltinInfo.getHeaderName(ID);
2380 return "stdio.h";
2382 return "setjmp.h";
2384 return "ucontext.h";
2385 }
2386 llvm_unreachable("unhandled error kind");
2387}
2388
2390 unsigned ID, SourceLocation Loc) {
2392
2393 if (getLangOpts().CPlusPlus) {
2395 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2396 CLinkageDecl->setImplicit();
2397 Parent->addDecl(CLinkageDecl);
2398 Parent = CLinkageDecl;
2399 }
2400
2401 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2402 /*TInfo=*/nullptr, SC_Extern,
2403 getCurFPFeatures().isFPConstrained(),
2404 false, Type->isFunctionProtoType());
2405 New->setImplicit();
2406 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2407
2408 // Create Decl objects for each parameter, adding them to the
2409 // FunctionDecl.
2410 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2412 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2414 Context, New, SourceLocation(), SourceLocation(), nullptr,
2415 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2416 parm->setScopeInfo(0, i);
2417 Params.push_back(parm);
2418 }
2419 New->setParams(Params);
2420 }
2421
2423 return New;
2424}
2425
2426/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2427/// file scope. lazily create a decl for it. ForRedeclaration is true
2428/// if we're creating this built-in in anticipation of redeclaring the
2429/// built-in.
2431 Scope *S, bool ForRedeclaration,
2432 SourceLocation Loc) {
2434
2436 QualType R = Context.GetBuiltinType(ID, Error);
2437 if (Error) {
2438 if (!ForRedeclaration)
2439 return nullptr;
2440
2441 // If we have a builtin without an associated type we should not emit a
2442 // warning when we were not able to find a type for it.
2443 if (Error == ASTContext::GE_Missing_type ||
2445 return nullptr;
2446
2447 // If we could not find a type for setjmp it is because the jmp_buf type was
2448 // not defined prior to the setjmp declaration.
2449 if (Error == ASTContext::GE_Missing_setjmp) {
2450 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2452 return nullptr;
2453 }
2454
2455 // Generally, we emit a warning that the declaration requires the
2456 // appropriate header.
2457 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2458 << getHeaderName(Context.BuiltinInfo, ID, Error)
2460 return nullptr;
2461 }
2462
2463 if (!ForRedeclaration &&
2466 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2467 : diag::ext_implicit_lib_function_decl)
2468 << Context.BuiltinInfo.getName(ID) << R;
2469 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2470 Diag(Loc, diag::note_include_header_or_declare)
2471 << Header << Context.BuiltinInfo.getName(ID);
2472 }
2473
2474 if (R.isNull())
2475 return nullptr;
2476
2477 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2479
2480 // TUScope is the translation-unit scope to insert this function into.
2481 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2482 // relate Scopes to DeclContexts, and probably eliminate CurContext
2483 // entirely, but we're not there yet.
2484 DeclContext *SavedContext = CurContext;
2485 CurContext = New->getDeclContext();
2487 CurContext = SavedContext;
2488 return New;
2489}
2490
2491/// Typedef declarations don't have linkage, but they still denote the same
2492/// entity if their types are the same.
2493/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2494/// isSameEntity.
2498 // This is only interesting when modules are enabled.
2499 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2500 return;
2501
2502 // Empty sets are uninteresting.
2503 if (Previous.empty())
2504 return;
2505
2506 LookupResult::Filter Filter = Previous.makeFilter();
2507 while (Filter.hasNext()) {
2508 NamedDecl *Old = Filter.next();
2509
2510 // Non-hidden declarations are never ignored.
2511 if (S.isVisible(Old))
2512 continue;
2513
2514 // Declarations of the same entity are not ignored, even if they have
2515 // different linkages.
2516 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2517 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2518 Decl->getUnderlyingType()))
2519 continue;
2520
2521 // If both declarations give a tag declaration a typedef name for linkage
2522 // purposes, then they declare the same entity.
2523 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2524 Decl->getAnonDeclWithTypedefName())
2525 continue;
2526 }
2527
2528 Filter.erase();
2529 }
2530
2531 Filter.done();
2532}
2533
2535 QualType OldType;
2536 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2537 OldType = OldTypedef->getUnderlyingType();
2538 else
2539 OldType = Context.getTypeDeclType(Old);
2540 QualType NewType = New->getUnderlyingType();
2541
2542 if (NewType->isVariablyModifiedType()) {
2543 // Must not redefine a typedef with a variably-modified type.
2544 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2545 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2546 << Kind << NewType;
2547 if (Old->getLocation().isValid())
2549 New->setInvalidDecl();
2550 return true;
2551 }
2552
2553 if (OldType != NewType &&
2554 !OldType->isDependentType() &&
2555 !NewType->isDependentType() &&
2556 !Context.hasSameType(OldType, NewType)) {
2557 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2558 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2559 << Kind << NewType << OldType;
2560 if (Old->getLocation().isValid())
2562 New->setInvalidDecl();
2563 return true;
2564 }
2565 return false;
2566}
2567
2568/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2569/// same name and scope as a previous declaration 'Old'. Figure out
2570/// how to resolve this situation, merging decls or emitting
2571/// diagnostics as appropriate. If there was an error, set New to be invalid.
2572///
2574 LookupResult &OldDecls) {
2575 // If the new decl is known invalid already, don't bother doing any
2576 // merging checks.
2577 if (New->isInvalidDecl()) return;
2578
2579 // Allow multiple definitions for ObjC built-in typedefs.
2580 // FIXME: Verify the underlying types are equivalent!
2581 if (getLangOpts().ObjC) {
2582 const IdentifierInfo *TypeID = New->getIdentifier();
2583 switch (TypeID->getLength()) {
2584 default: break;
2585 case 2:
2586 {
2587 if (!TypeID->isStr("id"))
2588 break;
2589 QualType T = New->getUnderlyingType();
2590 if (!T->isPointerType())
2591 break;
2592 if (!T->isVoidPointerType()) {
2593 QualType PT = T->castAs<PointerType>()->getPointeeType();
2594 if (!PT->isStructureType())
2595 break;
2596 }
2598 // Install the built-in type for 'id', ignoring the current definition.
2600 return;
2601 }
2602 case 5:
2603 if (!TypeID->isStr("Class"))
2604 break;
2606 // Install the built-in type for 'Class', ignoring the current definition.
2608 return;
2609 case 3:
2610 if (!TypeID->isStr("SEL"))
2611 break;
2613 // Install the built-in type for 'SEL', ignoring the current definition.
2615 return;
2616 }
2617 // Fall through - the typedef name was not a builtin type.
2618 }
2619
2620 // Verify the old decl was also a type.
2621 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2622 if (!Old) {
2623 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2624 << New->getDeclName();
2625
2626 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2627 if (OldD->getLocation().isValid())
2628 notePreviousDefinition(OldD, New->getLocation());
2629
2630 return New->setInvalidDecl();
2631 }
2632
2633 // If the old declaration is invalid, just give up here.
2634 if (Old->isInvalidDecl())
2635 return New->setInvalidDecl();
2636
2637 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2638 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2639 auto *NewTag = New->getAnonDeclWithTypedefName();
2640 NamedDecl *Hidden = nullptr;
2641 if (OldTag && NewTag &&
2642 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2643 !hasVisibleDefinition(OldTag, &Hidden)) {
2644 // There is a definition of this tag, but it is not visible. Use it
2645 // instead of our tag.
2646 New->setTypeForDecl(OldTD->getTypeForDecl());
2647 if (OldTD->isModed())
2648 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2649 OldTD->getUnderlyingType());
2650 else
2651 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2652
2653 // Make the old tag definition visible.
2655
2656 // If this was an unscoped enumeration, yank all of its enumerators
2657 // out of the scope.
2658 if (isa<EnumDecl>(NewTag)) {
2659 Scope *EnumScope = getNonFieldDeclScope(S);
2660 for (auto *D : NewTag->decls()) {
2661 auto *ED = cast<EnumConstantDecl>(D);
2662 assert(EnumScope->isDeclScope(ED));
2663 EnumScope->RemoveDecl(ED);
2665 ED->getLexicalDeclContext()->removeDecl(ED);
2666 }
2667 }
2668 }
2669 }
2670
2671 // If the typedef types are not identical, reject them in all languages and
2672 // with any extensions enabled.
2673 if (isIncompatibleTypedef(Old, New))
2674 return;
2675
2676 // The types match. Link up the redeclaration chain and merge attributes if
2677 // the old declaration was a typedef.
2678 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2679 New->setPreviousDecl(Typedef);
2680 mergeDeclAttributes(New, Old);
2681 }
2682
2683 if (getLangOpts().MicrosoftExt)
2684 return;
2685
2686 if (getLangOpts().CPlusPlus) {
2687 // C++ [dcl.typedef]p2:
2688 // In a given non-class scope, a typedef specifier can be used to
2689 // redefine the name of any type declared in that scope to refer
2690 // to the type to which it already refers.
2691 if (!isa<CXXRecordDecl>(CurContext))
2692 return;
2693
2694 // C++0x [dcl.typedef]p4:
2695 // In a given class scope, a typedef specifier can be used to redefine
2696 // any class-name declared in that scope that is not also a typedef-name
2697 // to refer to the type to which it already refers.
2698 //
2699 // This wording came in via DR424, which was a correction to the
2700 // wording in DR56, which accidentally banned code like:
2701 //
2702 // struct S {
2703 // typedef struct A { } A;
2704 // };
2705 //
2706 // in the C++03 standard. We implement the C++0x semantics, which
2707 // allow the above but disallow
2708 //
2709 // struct S {
2710 // typedef int I;
2711 // typedef int I;
2712 // };
2713 //
2714 // since that was the intent of DR56.
2715 if (!isa<TypedefNameDecl>(Old))
2716 return;
2717
2718 Diag(New->getLocation(), diag::err_redefinition)
2719 << New->getDeclName();
2721 return New->setInvalidDecl();
2722 }
2723
2724 // Modules always permit redefinition of typedefs, as does C11.
2725 if (getLangOpts().Modules || getLangOpts().C11)
2726 return;
2727
2728 // If we have a redefinition of a typedef in C, emit a warning. This warning
2729 // is normally mapped to an error, but can be controlled with
2730 // -Wtypedef-redefinition. If either the original or the redefinition is
2731 // in a system header, don't emit this for compatibility with GCC.
2732 if (getDiagnostics().getSuppressSystemWarnings() &&
2733 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2734 (Old->isImplicit() ||
2737 return;
2738
2739 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2740 << New->getDeclName();
2742}
2743
2744/// DeclhasAttr - returns true if decl Declaration already has the target
2745/// attribute.
2746static bool DeclHasAttr(const Decl *D, const Attr *A) {
2747 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2748 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2749 for (const auto *i : D->attrs())
2750 if (i->getKind() == A->getKind()) {
2751 if (Ann) {
2752 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2753 return true;
2754 continue;
2755 }
2756 // FIXME: Don't hardcode this check
2757 if (OA && isa<OwnershipAttr>(i))
2758 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2759 return true;
2760 }
2761
2762 return false;
2763}
2764
2766 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2767 return VD->isThisDeclarationADefinition();
2768 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2769 return TD->isCompleteDefinition() || TD->isBeingDefined();
2770 return true;
2771}
2772
2773/// Merge alignment attributes from \p Old to \p New, taking into account the
2774/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2775///
2776/// \return \c true if any attributes were added to \p New.
2777static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2778 // Look for alignas attributes on Old, and pick out whichever attribute
2779 // specifies the strictest alignment requirement.
2780 AlignedAttr *OldAlignasAttr = nullptr;
2781 AlignedAttr *OldStrictestAlignAttr = nullptr;
2782 unsigned OldAlign = 0;
2783 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2784 // FIXME: We have no way of representing inherited dependent alignments
2785 // in a case like:
2786 // template<int A, int B> struct alignas(A) X;
2787 // template<int A, int B> struct alignas(B) X {};
2788 // For now, we just ignore any alignas attributes which are not on the
2789 // definition in such a case.
2790 if (I->isAlignmentDependent())
2791 return false;
2792
2793 if (I->isAlignas())
2794 OldAlignasAttr = I;
2795
2796 unsigned Align = I->getAlignment(S.Context);
2797 if (Align > OldAlign) {
2798 OldAlign = Align;
2799 OldStrictestAlignAttr = I;
2800 }
2801 }
2802
2803 // Look for alignas attributes on New.
2804 AlignedAttr *NewAlignasAttr = nullptr;
2805 unsigned NewAlign = 0;
2806 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2807 if (I->isAlignmentDependent())
2808 return false;
2809
2810 if (I->isAlignas())
2811 NewAlignasAttr = I;
2812
2813 unsigned Align = I->getAlignment(S.Context);
2814 if (Align > NewAlign)
2815 NewAlign = Align;
2816 }
2817
2818 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2819 // Both declarations have 'alignas' attributes. We require them to match.
2820 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2821 // fall short. (If two declarations both have alignas, they must both match
2822 // every definition, and so must match each other if there is a definition.)
2823
2824 // If either declaration only contains 'alignas(0)' specifiers, then it
2825 // specifies the natural alignment for the type.
2826 if (OldAlign == 0 || NewAlign == 0) {
2827 QualType Ty;
2828 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2829 Ty = VD->getType();
2830 else
2831 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2832
2833 if (OldAlign == 0)
2834 OldAlign = S.Context.getTypeAlign(Ty);
2835 if (NewAlign == 0)
2836 NewAlign = S.Context.getTypeAlign(Ty);
2837 }
2838
2839 if (OldAlign != NewAlign) {
2840 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2843 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2844 }
2845 }
2846
2847 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2848 // C++11 [dcl.align]p6:
2849 // if any declaration of an entity has an alignment-specifier,
2850 // every defining declaration of that entity shall specify an
2851 // equivalent alignment.
2852 // C11 6.7.5/7:
2853 // If the definition of an object does not have an alignment
2854 // specifier, any other declaration of that object shall also
2855 // have no alignment specifier.
2856 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2857 << OldAlignasAttr;
2858 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2859 << OldAlignasAttr;
2860 }
2861
2862 bool AnyAdded = false;
2863
2864 // Ensure we have an attribute representing the strictest alignment.
2865 if (OldAlign > NewAlign) {
2866 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2867 Clone->setInherited(true);
2868 New->addAttr(Clone);
2869 AnyAdded = true;
2870 }
2871
2872 // Ensure we have an alignas attribute if the old declaration had one.
2873 if (OldAlignasAttr && !NewAlignasAttr &&
2874 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2875 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2876 Clone->setInherited(true);
2877 New->addAttr(Clone);
2878 AnyAdded = true;
2879 }
2880
2881 return AnyAdded;
2882}
2883
2884#define WANT_DECL_MERGE_LOGIC
2885#include "clang/Sema/AttrParsedAttrImpl.inc"
2886#undef WANT_DECL_MERGE_LOGIC
2887
2889 const InheritableAttr *Attr,
2891 // Diagnose any mutual exclusions between the attribute that we want to add
2892 // and attributes that already exist on the declaration.
2893 if (!DiagnoseMutualExclusions(S, D, Attr))
2894 return false;
2895
2896 // This function copies an attribute Attr from a previous declaration to the
2897 // new declaration D if the new declaration doesn't itself have that attribute
2898 // yet or if that attribute allows duplicates.
2899 // If you're adding a new attribute that requires logic different from
2900 // "use explicit attribute on decl if present, else use attribute from
2901 // previous decl", for example if the attribute needs to be consistent
2902 // between redeclarations, you need to call a custom merge function here.
2903 InheritableAttr *NewAttr = nullptr;
2904 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2905 NewAttr = S.mergeAvailabilityAttr(
2906 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2907 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2908 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2909 AA->getPriority());
2910 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2911 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2912 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2913 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2914 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2915 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2916 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2917 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2918 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2919 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2920 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2921 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2922 FA->getFirstArg());
2923 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2924 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2925 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2926 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2927 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2928 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2929 IA->getInheritanceModel());
2930 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2931 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2932 &S.Context.Idents.get(AA->getSpelling()));
2933 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2934 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2935 isa<CUDAGlobalAttr>(Attr))) {
2936 // CUDA target attributes are part of function signature for
2937 // overloading purposes and must not be merged.
2938 return false;
2939 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2940 NewAttr = S.mergeMinSizeAttr(D, *MA);
2941 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2942 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2943 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2944 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2945 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2946 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2947 else if (isa<AlignedAttr>(Attr))
2948 // AlignedAttrs are handled separately, because we need to handle all
2949 // such attributes on a declaration at the same time.
2950 NewAttr = nullptr;
2951 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2952 (AMK == Sema::AMK_Override ||
2955 NewAttr = nullptr;
2956 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2957 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2958 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2959 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2960 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2961 NewAttr = S.mergeImportNameAttr(D, *INA);
2962 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2963 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2964 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2965 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2966 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2967 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2968 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2969 NewAttr =
2970 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
2971 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2972 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
2973 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2974 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2975
2976 if (NewAttr) {
2977 NewAttr->setInherited(true);
2978 D->addAttr(NewAttr);
2979 if (isa<MSInheritanceAttr>(NewAttr))
2980 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2981 return true;
2982 }
2983
2984 return false;
2985}
2986
2987static const NamedDecl *getDefinition(const Decl *D) {
2988 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2989 return TD->getDefinition();
2990 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2991 const VarDecl *Def = VD->getDefinition();
2992 if (Def)
2993 return Def;
2994 return VD->getActingDefinition();
2995 }
2996 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2997 const FunctionDecl *Def = nullptr;
2998 if (FD->isDefined(Def, true))
2999 return Def;
3000 }
3001 return nullptr;
3002}
3003
3004static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3005 for (const auto *Attribute : D->attrs())
3006 if (Attribute->getKind() == Kind)
3007 return true;
3008 return false;
3009}
3010
3011/// checkNewAttributesAfterDef - If we already have a definition, check that
3012/// there are no new attributes in this declaration.
3013static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3014 if (!New->hasAttrs())
3015 return;
3016
3017 const NamedDecl *Def = getDefinition(Old);
3018 if (!Def || Def == New)
3019 return;
3020
3021 AttrVec &NewAttributes = New->getAttrs();
3022 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3023 const Attr *NewAttribute = NewAttributes[I];
3024
3025 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3026 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3027 Sema::SkipBodyInfo SkipBody;
3028 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3029
3030 // If we're skipping this definition, drop the "alias" attribute.
3031 if (SkipBody.ShouldSkip) {
3032 NewAttributes.erase(NewAttributes.begin() + I);
3033 --E;
3034 continue;
3035 }
3036 } else {
3037 VarDecl *VD = cast<VarDecl>(New);
3038 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3040 ? diag::err_alias_after_tentative
3041 : diag::err_redefinition;
3042 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3043 if (Diag == diag::err_redefinition)
3044 S.notePreviousDefinition(Def, VD->getLocation());
3045 else
3046 S.Diag(Def->getLocation(), diag::note_previous_definition);
3047 VD->setInvalidDecl();
3048 }
3049 ++I;
3050 continue;
3051 }
3052
3053 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3054 // Tentative definitions are only interesting for the alias check above.
3055 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3056 ++I;
3057 continue;
3058 }
3059 }
3060
3061 if (hasAttribute(Def, NewAttribute->getKind())) {
3062 ++I;
3063 continue; // regular attr merging will take care of validating this.
3064 }
3065
3066 if (isa<C11NoReturnAttr>(NewAttribute)) {
3067 // C's _Noreturn is allowed to be added to a function after it is defined.
3068 ++I;
3069 continue;
3070 } else if (isa<UuidAttr>(NewAttribute)) {
3071 // msvc will allow a subsequent definition to add an uuid to a class
3072 ++I;
3073 continue;
3074 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3075 if (AA->isAlignas()) {
3076 // C++11 [dcl.align]p6:
3077 // if any declaration of an entity has an alignment-specifier,
3078 // every defining declaration of that entity shall specify an
3079 // equivalent alignment.
3080 // C11 6.7.5/7:
3081 // If the definition of an object does not have an alignment
3082 // specifier, any other declaration of that object shall also
3083 // have no alignment specifier.
3084 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3085 << AA;
3086 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3087 << AA;
3088 NewAttributes.erase(NewAttributes.begin() + I);
3089 --E;
3090 continue;
3091 }
3092 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3093 // If there is a C definition followed by a redeclaration with this
3094 // attribute then there are two different definitions. In C++, prefer the
3095 // standard diagnostics.
3096 if (!S.getLangOpts().CPlusPlus) {
3097 S.Diag(NewAttribute->getLocation(),
3098 diag::err_loader_uninitialized_redeclaration);
3099 S.Diag(Def->getLocation(), diag::note_previous_definition);
3100 NewAttributes.erase(NewAttributes.begin() + I);
3101 --E;
3102 continue;
3103 }
3104 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3105 cast<VarDecl>(New)->isInline() &&
3106 !cast<VarDecl>(New)->isInlineSpecified()) {
3107 // Don't warn about applying selectany to implicitly inline variables.
3108 // Older compilers and language modes would require the use of selectany
3109 // to make such variables inline, and it would have no effect if we
3110 // honored it.
3111 ++I;
3112 continue;
3113 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3114 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3115 // declarations after definitions.
3116 ++I;
3117 continue;
3118 }
3119
3120 S.Diag(NewAttribute->getLocation(),
3121 diag::warn_attribute_precede_definition);
3122 S.Diag(Def->getLocation(), diag::note_previous_definition);
3123 NewAttributes.erase(NewAttributes.begin() + I);
3124 --E;
3125 }
3126}
3127
3128static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3129 const ConstInitAttr *CIAttr,
3130 bool AttrBeforeInit) {
3131 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3132
3133 // Figure out a good way to write this specifier on the old declaration.
3134 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3135 // enough of the attribute list spelling information to extract that without
3136 // heroics.
3137 std::string SuitableSpelling;
3138 if (S.getLangOpts().CPlusPlus20)
3139 SuitableSpelling = std::string(
3140 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3141 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3142 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3143 InsertLoc, {tok::l_square, tok::l_square,
3144 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3145 S.PP.getIdentifierInfo("require_constant_initialization"),
3146 tok::r_square, tok::r_square}));
3147 if (SuitableSpelling.empty())
3148 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3149 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3150 S.PP.getIdentifierInfo("require_constant_initialization"),
3151 tok::r_paren, tok::r_paren}));
3152 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3153 SuitableSpelling = "constinit";
3154 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3155 SuitableSpelling = "[[clang::require_constant_initialization]]";
3156 if (SuitableSpelling.empty())
3157 SuitableSpelling = "__attribute__((require_constant_initialization))";
3158 SuitableSpelling += " ";
3159
3160 if (AttrBeforeInit) {
3161 // extern constinit int a;
3162 // int a = 0; // error (missing 'constinit'), accepted as extension
3163 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3164 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3165 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3166 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3167 } else {
3168 // int a = 0;
3169 // constinit extern int a; // error (missing 'constinit')
3170 S.Diag(CIAttr->getLocation(),
3171 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3172 : diag::warn_require_const_init_added_too_late)
3173 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3174 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3175 << CIAttr->isConstinit()
3176 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3177 }
3178}
3179
3180/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3183 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3184 UsedAttr *NewAttr = OldAttr->clone(Context);
3185 NewAttr->setInherited(true);
3186 New->addAttr(NewAttr);
3187 }
3188 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3189 RetainAttr *NewAttr = OldAttr->clone(Context);
3190 NewAttr->setInherited(true);
3191 New->addAttr(NewAttr);
3192 }
3193
3194 if (!Old->hasAttrs() && !New->hasAttrs())
3195 return;
3196
3197 // [dcl.constinit]p1:
3198 // If the [constinit] specifier is applied to any declaration of a
3199 // variable, it shall be applied to the initializing declaration.
3200 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3201 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3202 if (bool(OldConstInit) != bool(NewConstInit)) {
3203 const auto *OldVD = cast<VarDecl>(Old);
3204 auto *NewVD = cast<VarDecl>(New);
3205
3206 // Find the initializing declaration. Note that we might not have linked
3207 // the new declaration into the redeclaration chain yet.
3208 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3209 if (!InitDecl &&
3210 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3211 InitDecl = NewVD;
3212
3213 if (InitDecl == NewVD) {
3214 // This is the initializing declaration. If it would inherit 'constinit',
3215 // that's ill-formed. (Note that we do not apply this to the attribute
3216 // form).
3217 if (OldConstInit && OldConstInit->isConstinit())
3218 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3219 /*AttrBeforeInit=*/true);
3220 } else if (NewConstInit) {
3221 // This is the first time we've been told that this declaration should
3222 // have a constant initializer. If we already saw the initializing
3223 // declaration, this is too late.
3224 if (InitDecl && InitDecl != NewVD) {
3225 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3226 /*AttrBeforeInit=*/false);
3227 NewVD->dropAttr<ConstInitAttr>();
3228 }
3229 }
3230 }
3231
3232 // Attributes declared post-definition are currently ignored.
3233 checkNewAttributesAfterDef(*this, New, Old);
3234
3235 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3236 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3237 if (!OldA->isEquivalent(NewA)) {
3238 // This redeclaration changes __asm__ label.
3239 Diag(New->getLocation(), diag::err_different_asm_label);
3240 Diag(OldA->getLocation(), diag::note_previous_declaration);
3241 }
3242 } else if (Old->isUsed()) {
3243 // This redeclaration adds an __asm__ label to a declaration that has
3244 // already been ODR-used.
3245 Diag(New->getLocation(), diag::err_late_asm_label_name)
3246 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3247 }
3248 }
3249
3250 // Re-declaration cannot add abi_tag's.
3251 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3252 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3253 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3254 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3255 Diag(NewAbiTagAttr->getLocation(),
3256 diag::err_new_abi_tag_on_redeclaration)
3257 << NewTag;
3258 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3259 }
3260 }
3261 } else {
3262 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3263 Diag(Old->getLocation(), diag::note_previous_declaration);
3264 }
3265 }
3266
3267 // This redeclaration adds a section attribute.
3268 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3269 if (auto *VD = dyn_cast<VarDecl>(New)) {
3270 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3271 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3272 Diag(Old->getLocation(), diag::note_previous_declaration);
3273 }
3274 }
3275 }
3276
3277 // Redeclaration adds code-seg attribute.
3278 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3279 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3280 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3281 Diag(New->getLocation(), diag::warn_mismatched_section)
3282 << 0 /*codeseg*/;
3283 Diag(Old->getLocation(), diag::note_previous_declaration);
3284 }
3285
3286 if (!Old->hasAttrs())
3287 return;
3288
3289 bool foundAny = New->hasAttrs();
3290
3291 // Ensure that any moving of objects within the allocated map is done before
3292 // we process them.
3293 if (!foundAny) New->setAttrs(AttrVec());
3294
3295 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3296 // Ignore deprecated/unavailable/availability attributes if requested.
3298 if (isa<DeprecatedAttr>(I) ||
3299 isa<UnavailableAttr>(I) ||
3300 isa<AvailabilityAttr>(I)) {
3301 switch (AMK) {
3302 case AMK_None:
3303 continue;
3304
3305 case AMK_Redeclaration:
3306 case AMK_Override:
3309 LocalAMK = AMK;
3310 break;
3311 }
3312 }
3313
3314 // Already handled.
3315 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3316 continue;
3317
3318 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3319 foundAny = true;
3320 }
3321
3322 if (mergeAlignedAttrs(*this, New, Old))
3323 foundAny = true;
3324
3325 if (!foundAny) New->dropAttrs();
3326}
3327
3328/// mergeParamDeclAttributes - Copy attributes from the old parameter
3329/// to the new one.
3331 const ParmVarDecl *oldDecl,
3332 Sema &S) {
3333 // C++11 [dcl.attr.depend]p2:
3334 // The first declaration of a function shall specify the
3335 // carries_dependency attribute for its declarator-id if any declaration
3336 // of the function specifies the carries_dependency attribute.
3337 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3338 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3339 S.Diag(CDA->getLocation(),
3340 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3341 // Find the first declaration of the parameter.
3342 // FIXME: Should we build redeclaration chains for function parameters?
3343 const FunctionDecl *FirstFD =
3344 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3345 const ParmVarDecl *FirstVD =
3346 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3347 S.Diag(FirstVD->getLocation(),
3348 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3349 }
3350
3351 if (!oldDecl->hasAttrs())
3352 return;
3353
3354 bool foundAny = newDecl->hasAttrs();
3355
3356 // Ensure that any moving of objects within the allocated map is
3357 // done before we process them.
3358 if (!foundAny) newDecl->setAttrs(AttrVec());
3359
3360 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3361 if (!DeclHasAttr(newDecl, I)) {
3362 InheritableAttr *newAttr =
3364 newAttr->setInherited(true);
3365 newDecl->addAttr(newAttr);
3366 foundAny = true;
3367 }
3368 }
3369
3370 if (!foundAny) newDecl->dropAttrs();
3371}
3372
3374 const ASTContext &Ctx) {
3375
3376 auto NoSizeInfo = [&Ctx](QualType Ty) {
3377 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3378 return true;
3379 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3380 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
3381 return false;
3382 };
3383
3384 // `type[]` is equivalent to `type *` and `type[*]`.
3385 if (NoSizeInfo(Old) && NoSizeInfo(New))
3386 return true;
3387
3388 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3389 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3390 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3391 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3392 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
3393 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
3394 return false;
3395 return true;
3396 }
3397
3398 // Only compare size, ignore Size modifiers and CVR.
3399 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3400 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3401 Ctx.getAsConstantArrayType(New)->getSize();
3402 }
3403
3404 // Don't try to compare dependent sized array
3406 return true;
3407 }
3408
3409 return Old == New;
3410}
3411
3412static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3413 const ParmVarDecl *OldParam,
3414 Sema &S) {
3415 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3416 if (auto Newnullability = NewParam->getType()->getNullability()) {
3417 if (*Oldnullability != *Newnullability) {
3418 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3420 *Newnullability,
3422 != 0))
3424 *Oldnullability,
3426 != 0));
3427 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3428 }
3429 } else {
3430 QualType NewT = NewParam->getType();
3431 NewT = S.Context.getAttributedType(
3432 AttributedType::getNullabilityAttrKind(*Oldnullability),
3433 NewT, NewT);
3434 NewParam->setType(NewT);
3435 }
3436 }
3437 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3438 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3439 if (OldParamDT && NewParamDT &&
3440 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3441 QualType OldParamOT = OldParamDT->getOriginalType();
3442 QualType NewParamOT = NewParamDT->getOriginalType();
3443 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3444 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3445 << NewParam << NewParamOT;
3446 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3447 << OldParamOT;
3448 }
3449 }
3450}
3451
3452namespace {
3453
3454/// Used in MergeFunctionDecl to keep track of function parameters in
3455/// C.
3456struct GNUCompatibleParamWarning {
3457 ParmVarDecl *OldParm;
3458 ParmVarDecl *NewParm;
3459 QualType PromotedType;
3460};
3461
3462} // end anonymous namespace
3463
3464// Determine whether the previous declaration was a definition, implicit
3465// declaration, or a declaration.
3466template <typename T>
3467static std::pair<diag::kind, SourceLocation>
3468getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3469 diag::kind PrevDiag;
3470 SourceLocation OldLocation = Old->getLocation();
3471 if (Old->isThisDeclarationADefinition())
3472 PrevDiag = diag::note_previous_definition;
3473 else if (Old->isImplicit()) {
3474 PrevDiag = diag::note_previous_implicit_declaration;
3475 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3476 if (FD->getBuiltinID())
3477 PrevDiag = diag::note_previous_builtin_declaration;
3478 }
3479 if (OldLocation.isInvalid())
3480 OldLocation = New->getLocation();
3481 } else
3482 PrevDiag = diag::note_previous_declaration;
3483 return std::make_pair(PrevDiag, OldLocation);
3484}
3485
3486/// canRedefineFunction - checks if a function can be redefined. Currently,
3487/// only extern inline functions can be redefined, and even then only in
3488/// GNU89 mode.
3489static bool canRedefineFunction(const FunctionDecl *FD,
3490 const LangOptions& LangOpts) {
3491 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3492 !LangOpts.CPlusPlus &&
3493 FD->isInlineSpecified() &&
3494 FD->getStorageClass() == SC_Extern);
3495}
3496
3497const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3498 const AttributedType *AT = T->getAs<AttributedType>();
3499 while (AT && !AT->isCallingConv())
3500 AT = AT->getModifiedType()->getAs<AttributedType>();
3501 return AT;
3502}
3503
3504template <typename T>
3505static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3506 const DeclContext *DC = Old->getDeclContext();
3507 if (DC->isRecord())
3508 return false;
3509
3510 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3511 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3512 return true;
3513 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3514 return true;
3515 return false;
3516}
3517
3518template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3519static bool isExternC(VarTemplateDecl *) { return false; }
3520static bool isExternC(FunctionTemplateDecl *) { return false; }
3521
3522/// Check whether a redeclaration of an entity introduced by a
3523/// using-declaration is valid, given that we know it's not an overload
3524/// (nor a hidden tag declaration).
3525template<typename ExpectedDecl>
3527 ExpectedDecl *New) {
3528 // C++11 [basic.scope.declarative]p4:
3529 // Given a set of declarations in a single declarative region, each of
3530 // which specifies the same unqualified name,
3531 // -- they shall all refer to the same entity, or all refer to functions
3532 // and function templates; or
3533 // -- exactly one declaration shall declare a class name or enumeration
3534 // name that is not a typedef name and the other declarations shall all
3535 // refer to the same variable or enumerator, or all refer to functions
3536 // and function templates; in this case the class name or enumeration
3537 // name is hidden (3.3.10).
3538
3539 // C++11 [namespace.udecl]p14:
3540 // If a function declaration in namespace scope or block scope has the
3541 // same name and the same parameter-type-list as a function introduced
3542 // by a using-declaration, and the declarations do not declare the same
3543 // function, the program is ill-formed.
3544
3545 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3546 if (Old &&
3547 !Old->getDeclContext()->getRedeclContext()->Equals(
3548 New->getDeclContext()->getRedeclContext()) &&
3549 !(isExternC(Old) && isExternC(New)))
3550 Old = nullptr;
3551
3552 if (!Old) {
3553 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3554 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3555 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3556 return true;
3557 }
3558 return false;
3559}
3560
3562 const FunctionDecl *B) {
3563 assert(A->getNumParams() == B->getNumParams());
3564
3565 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3566 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3567 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3568 if (AttrA == AttrB)
3569 return true;
3570 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3571 AttrA->isDynamic() == AttrB->isDynamic();
3572 };
3573
3574 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3575}
3576
3577/// If necessary, adjust the semantic declaration context for a qualified
3578/// declaration to name the correct inline namespace within the qualifier.
3580 DeclaratorDecl *OldD) {
3581 // The only case where we need to update the DeclContext is when
3582 // redeclaration lookup for a qualified name finds a declaration
3583 // in an inline namespace within the context named by the qualifier:
3584 //
3585 // inline namespace N { int f(); }
3586 // int ::f(); // Sema DC needs adjusting from :: to N::.
3587 //
3588 // For unqualified declarations, the semantic context *can* change
3589 // along the redeclaration chain (for local extern declarations,
3590 // extern "C" declarations, and friend declarations in particular).
3591 if (!NewD->getQualifier())
3592 return;
3593
3594 // NewD is probably already in the right context.
3595 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3596 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3597 if (NamedDC->Equals(SemaDC))
3598 return;
3599
3600 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3601 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3602 "unexpected context for redeclaration");
3603
3604 auto *LexDC = NewD->getLexicalDeclContext();
3605 auto FixSemaDC = [=](NamedDecl *D) {
3606 if (!D)
3607 return;
3608 D->setDeclContext(SemaDC);
3609 D->setLexicalDeclContext(LexDC);
3610 };
3611
3612 FixSemaDC(NewD);
3613 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3614 FixSemaDC(FD->getDescribedFunctionTemplate());
3615 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3616 FixSemaDC(VD->getDescribedVarTemplate());
3617}
3618
3619/// MergeFunctionDecl - We just parsed a function 'New' from
3620/// declarator D which has the same name and scope as a previous
3621/// declaration 'Old'. Figure out how to resolve this situation,
3622/// merging decls or emitting diagnostics as appropriate.
3623///
3624/// In C++, New and Old must be declarations that are not
3625/// overloaded. Use IsOverload to determine whether New and Old are
3626/// overloaded, and to select the Old declaration that New should be
3627/// merged with.
3628///
3629/// Returns true if there was an error, false otherwise.
3631 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3632 // Verify the old decl was also a function.
3633 FunctionDecl *Old = OldD->getAsFunction();
3634 if (!Old) {
3635 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3636 if (New->getFriendObjectKind()) {
3637 Diag(New->getLocation(), diag::err_using_decl_friend);
3638 Diag(Shadow->getTargetDecl()->getLocation(),
3639 diag::note_using_decl_target);
3640 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3641 << 0;
3642 return true;
3643 }
3644
3645 // Check whether the two declarations might declare the same function or
3646 // function template.
3647 if (FunctionTemplateDecl *NewTemplate =
3650 NewTemplate))
3651 return true;
3652 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3653 ->getAsFunction();
3654 } else {
3655 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3656 return true;
3657 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3658 }
3659 } else {
3660 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3661 << New->getDeclName();
3662 notePreviousDefinition(OldD, New->getLocation());
3663 return true;
3664 }
3665 }
3666
3667 // If the old declaration was found in an inline namespace and the new
3668 // declaration was qualified, update the DeclContext to match.
3670
3671 // If the old declaration is invalid, just give up here.
3672 if (Old->isInvalidDecl())
3673 return true;
3674
3675 // Disallow redeclaration of some builtins.
3676 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3677 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3678 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3679 << Old << Old->getType();
3680 return true;
3681 }
3682
3683 diag::kind PrevDiag;
3684 SourceLocation OldLocation;
3685 std::tie(PrevDiag, OldLocation) =
3687
3688 // Don't complain about this if we're in GNU89 mode and the old function
3689 // is an extern inline function.
3690 // Don't complain about specializations. They are not supposed to have
3691 // storage classes.
3692 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3693 New->getStorageClass() == SC_Static &&
3694 Old->hasExternalFormalLinkage() &&
3697 if (getLangOpts().MicrosoftExt) {
3698 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3699 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3700 } else {
3701 Diag(New->getLocation(), diag::err_static_non_static) << New;
3702 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3703 return true;
3704 }
3705 }
3706
3707 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3708 if (!Old->hasAttr<InternalLinkageAttr>()) {
3709 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3710 << ILA;
3711 Diag(Old->getLocation(), diag::note_previous_declaration);
3712 New->dropAttr<InternalLinkageAttr>();
3713 }
3714
3715 if (auto *EA = New->getAttr<ErrorAttr>()) {
3716 if (!Old->hasAttr<ErrorAttr>()) {
3717 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3718 Diag(Old->getLocation(), diag::note_previous_declaration);
3719 New->dropAttr<ErrorAttr>();
3720 }
3721 }
3722
3723 if (CheckRedeclarationInModule(New, Old))
3724 return true;
3725
3726 if (!getLangOpts().CPlusPlus) {
3727 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3728 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3729 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3730 << New << OldOvl;
3731
3732 // Try our best to find a decl that actually has the overloadable
3733 // attribute for the note. In most cases (e.g. programs with only one
3734 // broken declaration/definition), this won't matter.
3735 //
3736 // FIXME: We could do this if we juggled some extra state in
3737 // OverloadableAttr, rather than just removing it.
3738 const Decl *DiagOld = Old;
3739 if (OldOvl) {
3740 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3741 const auto *A = D->getAttr<OverloadableAttr>();
3742 return A && !A->isImplicit();
3743 });
3744 // If we've implicitly added *all* of the overloadable attrs to this
3745 // chain, emitting a "previous redecl" note is pointless.
3746 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3747 }
3748
3749 if (DiagOld)
3750 Diag(DiagOld->getLocation(),
3751 diag::note_attribute_overloadable_prev_overload)
3752 << OldOvl;
3753
3754 if (OldOvl)
3755 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3756 else
3757 New->dropAttr<OverloadableAttr>();
3758 }
3759 }
3760
3761 // If a function is first declared with a calling convention, but is later
3762 // declared or defined without one, all following decls assume the calling
3763 // convention of the first.
3764 //
3765 // It's OK if a function is first declared without a calling convention,
3766 // but is later declared or defined with the default calling convention.
3767 //
3768 // To test if either decl has an explicit calling convention, we look for
3769 // AttributedType sugar nodes on the type as written. If they are missing or
3770 // were canonicalized away, we assume the calling convention was implicit.
3771 //
3772 // Note also that we DO NOT return at this point, because we still have
3773 // other tests to run.
3774 QualType OldQType = Context.getCanonicalType(Old->getType());
3775 QualType NewQType = Context.getCanonicalType(New->getType());
3776 const FunctionType *OldType = cast<FunctionType>(OldQType);
3777 const FunctionType *NewType = cast<FunctionType>(NewQType);
3778 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3779 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3780 bool RequiresAdjustment = false;
3781
3782 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3784 const FunctionType *FT =
3785 First->getType().getCanonicalType()->castAs<FunctionType>();
3787 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3788 if (!NewCCExplicit) {
3789 // Inherit the CC from the previous declaration if it was specified
3790 // there but not here.
3791 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3792 RequiresAdjustment = true;
3793 } else if (Old->getBuiltinID()) {
3794 // Builtin attribute isn't propagated to the new one yet at this point,
3795 // so we check if the old one is a builtin.
3796
3797 // Calling Conventions on a Builtin aren't really useful and setting a
3798 // default calling convention and cdecl'ing some builtin redeclarations is
3799 // common, so warn and ignore the calling convention on the redeclaration.
3800 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3801 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3803 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3804 RequiresAdjustment = true;
3805 } else {
3806 // Calling conventions aren't compatible, so complain.
3807 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3808 Diag(New->getLocation(), diag::err_cconv_change)
3809 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3810 << !FirstCCExplicit
3811 << (!FirstCCExplicit ? "" :
3813
3814 // Put the note on the first decl, since it is the one that matters.
3815 Diag(First->getLocation(), diag::note_previous_declaration);
3816 return true;
3817 }
3818 }
3819
3820 // FIXME: diagnose the other way around?
3821 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3822 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3823 RequiresAdjustment = true;
3824 }
3825
3826 // Merge regparm attribute.
3827 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3828 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3829 if (NewTypeInfo.getHasRegParm()) {
3830 Diag(New->getLocation(), diag::err_regparm_mismatch)
3831 << NewType->getRegParmType()
3832 << OldType->getRegParmType();
3833 Diag(OldLocation, diag::note_previous_declaration);
3834 return true;
3835 }
3836
3837 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3838 RequiresAdjustment = true;
3839 }
3840
3841 // Merge ns_returns_retained attribute.
3842 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3843 if (NewTypeInfo.getProducesResult()) {
3844 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3845 << "'ns_returns_retained'";
3846 Diag(OldLocation, diag::note_previous_declaration);
3847 return true;
3848 }
3849
3850 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3851 RequiresAdjustment = true;
3852 }
3853
3854 if (OldTypeInfo.getNoCallerSavedRegs() !=
3855 NewTypeInfo.getNoCallerSavedRegs()) {
3856 if (NewTypeInfo.getNoCallerSavedRegs()) {
3857 AnyX86NoCallerSavedRegistersAttr *Attr =
3858 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3859 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3860 Diag(OldLocation, diag::note_previous_declaration);
3861 return true;
3862 }
3863
3864 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3865 RequiresAdjustment = true;
3866 }
3867
3868 if (RequiresAdjustment) {
3871 New->setType(QualType(AdjustedType, 0));
3872 NewQType = Context.getCanonicalType(New->getType());
3873 }
3874
3875 // If this redeclaration makes the function inline, we may need to add it to
3876 // UndefinedButUsed.
3877 if (!Old->isInlined() && New->isInlined() &&
3878 !New->hasAttr<GNUInlineAttr>() &&
3879 !getLangOpts().GNUInline &&
3880 Old->isUsed(false) &&
3881 !Old->isDefined() && !New->isThisDeclarationADefinition())
3882 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3883 SourceLocation()));
3884
3885 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3886 // about it.
3887 if (New->hasAttr<GNUInlineAttr>() &&
3888 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3889 UndefinedButUsed.erase(Old->getCanonicalDecl());
3890 }
3891
3892 // If pass_object_size params don't match up perfectly, this isn't a valid
3893 // redeclaration.
3894 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3896 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3897 << New->getDeclName();
3898 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3899 return true;
3900 }
3901
3902 if (getLangOpts().CPlusPlus) {
3903 // C++1z [over.load]p2
3904 // Certain function declarations cannot be overloaded:
3905 // -- Function declarations that differ only in the return type,
3906 // the exception specification, or both cannot be overloaded.
3907
3908 // Check the exception specifications match. This may recompute the type of
3909 // both Old and New if it resolved exception specifications, so grab the
3910 // types again after this. Because this updates the type, we do this before
3911 // any of the other checks below, which may update the "de facto" NewQType
3912 // but do not necessarily update the type of New.
3913 if (CheckEquivalentExceptionSpec(Old, New))
3914 return true;
3915 OldQType = Context.getCanonicalType(Old->getType());
3916 NewQType = Context.getCanonicalType(New->getType());
3917
3918 // Go back to the type source info to compare the declared return types,
3919 // per C++1y [dcl.type.auto]p13:
3920 // Redeclarations or specializations of a function or function template
3921 // with a declared return type that uses a placeholder type shall also
3922 // use that placeholder, not a deduced type.
3923 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3924 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3925 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3926 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3927 OldDeclaredReturnType)) {
3928 QualType ResQT;
3929 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3930 OldDeclaredReturnType->isObjCObjectPointerType())
3931 // FIXME: This does the wrong thing for a deduced return type.
3932 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3933 if (ResQT.isNull()) {
3934 if (New->isCXXClassMember() && New->isOutOfLine())
3935 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3936 << New << New->getReturnTypeSourceRange();
3937 else
3938 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3939 << New->getReturnTypeSourceRange();
3940 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3941 << Old->getReturnTypeSourceRange();
3942 return true;
3943 }
3944 else
3945 NewQType = ResQT;
3946 }
3947
3948 QualType OldReturnType = OldType->getReturnType();
3949 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3950 if (OldReturnType != NewReturnType) {
3951 // If this function has a deduced return type and has already been
3952 // defined, copy the deduced value from the old declaration.
3953 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3954 if (OldAT && OldAT->isDeduced()) {
3955 QualType DT = OldAT->getDeducedType();
3956 if (DT.isNull()) {
3958 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3959 } else {
3960 New->setType(SubstAutoType(New->getType(), DT));
3961 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3962 }
3963 }
3964 }
3965
3966 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3967 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3968 if (OldMethod && NewMethod) {
3969 // Preserve triviality.
3970 NewMethod->setTrivial(OldMethod->isTrivial());
3971
3972 // MSVC allows explicit template specialization at class scope:
3973 // 2 CXXMethodDecls referring to the same function will be injected.
3974 // We don't want a redeclaration error.
3975 bool IsClassScopeExplicitSpecialization =
3976 OldMethod->isFunctionTemplateSpecialization() &&
3978 bool isFriend = NewMethod->getFriendObjectKind();
3979
3980 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3981 !IsClassScopeExplicitSpecialization) {
3982 // -- Member function declarations with the same name and the
3983 // same parameter types cannot be overloaded if any of them
3984 // is a static member function declaration.
3985 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3986 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3987 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3988 return true;
3989 }
3990
3991 // C++ [class.mem]p1:
3992 // [...] A member shall not be declared twice in the
3993 // member-specification, except that a nested class or member
3994 // class template can be declared and then later defined.
3995 if (!inTemplateInstantiation()) {
3996 unsigned NewDiag;
3997 if (isa<CXXConstructorDecl>(OldMethod))
3998 NewDiag = diag::err_constructor_redeclared;
3999 else if (isa<CXXDestructorDecl>(NewMethod))
4000 NewDiag = diag::err_destructor_redeclared;
4001 else if (isa<CXXConversionDecl>(NewMethod))
4002 NewDiag = diag::err_conv_function_redeclared;
4003 else
4004 NewDiag = diag::err_member_redeclared;
4005
4006 Diag(New->getLocation(), NewDiag);
4007 } else {
4008 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4009 << New << New->getType();
4010 }
4011 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4012 return true;
4013
4014 // Complain if this is an explicit declaration of a special
4015 // member that was initially declared implicitly.
4016 //
4017 // As an exception, it's okay to befriend such methods in order
4018 // to permit the implicit constructor/destructor/operator calls.
4019 } else if (OldMethod->isImplicit()) {
4020 if (isFriend) {
4021 NewMethod->setImplicit();
4022 } else {
4023 Diag(NewMethod->getLocation(),
4024 diag::err_definition_of_implicitly_declared_member)
4025 << New << getSpecialMember(OldMethod);
4026 return true;
4027 }
4028 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4029 Diag(NewMethod->getLocation(),
4030 diag::err_definition_of_explicitly_defaulted_member)
4031 << getSpecialMember(OldMethod);
4032 return true;
4033 }
4034 }
4035
4036 // C++11 [dcl.attr.noreturn]p1:
4037 // The first declaration of a function shall specify the noreturn
4038 // attribute if any declaration of that function specifies the noreturn
4039 // attribute.
4040 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4041 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4042 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4043 << NRA;
4044 Diag(Old->getLocation(), diag::note_previous_declaration);
4045 }
4046
4047 // C++11 [dcl.attr.depend]p2:
4048 // The first declaration of a function shall specify the
4049 // carries_dependency attribute for its declarator-id if any declaration
4050 // of the function specifies the carries_dependency attribute.
4051 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4052 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4053 Diag(CDA->getLocation(),
4054 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4055 Diag(Old->getFirstDecl()->getLocation(),
4056 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4057 }
4058
4059 // (C++98 8.3.5p3):
4060 // All declarations for a function shall agree exactly in both the
4061 // return type and the parameter-type-list.
4062 // We also want to respect all the extended bits except noreturn.
4063
4064 // noreturn should now match unless the old type info didn't have it.
4065 QualType OldQTypeForComparison = OldQType;
4066 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4067 auto *OldType = OldQType->castAs<FunctionProtoType>();
4068 const FunctionType *OldTypeForComparison
4069 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4070 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4071 assert(OldQTypeForComparison.isCanonical());
4072 }
4073
4074 if (haveIncompatibleLanguageLinkages(Old, New)) {
4075 // As a special case, retain the language linkage from previous
4076 // declarations of a friend function as an extension.
4077 //
4078 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4079 // and is useful because there's otherwise no way to specify language
4080 // linkage within class scope.
4081 //
4082 // Check cautiously as the friend object kind isn't yet complete.
4083 if (New->getFriendObjectKind() != Decl::FOK_None) {
4084 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4085 Diag(OldLocation, PrevDiag);
4086 } else {
4087 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4088 Diag(OldLocation, PrevDiag);
4089 return true;
4090 }
4091 }
4092
4093 // If the function types are compatible, merge the declarations. Ignore the
4094 // exception specifier because it was already checked above in
4095 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4096 // about incompatible types under -fms-compatibility.
4097 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4098 NewQType))
4099 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4100
4101 // If the types are imprecise (due to dependent constructs in friends or
4102 // local extern declarations), it's OK if they differ. We'll check again
4103 // during instantiation.
4104 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4105 return false;
4106
4107 // Fall through for conflicting redeclarations and redefinitions.
4108 }
4109
4110 // C: Function types need to be compatible, not identical. This handles
4111 // duplicate function decls like "void f(int); void f(enum X);" properly.
4112 if (!getLangOpts().CPlusPlus) {
4113 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4114 // type is specified by a function definition that contains a (possibly
4115 // empty) identifier list, both shall agree in the number of parameters
4116 // and the type of each parameter shall be compatible with the type that
4117 // results from the application of default argument promotions to the
4118 // type of the corresponding identifier. ...
4119 // This cannot be handled by ASTContext::typesAreCompatible() because that
4120 // doesn't know whether the function type is for a definition or not when
4121 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4122 // we need to cover here is that the number of arguments agree as the
4123 // default argument promotion rules were already checked by
4124 // ASTContext::typesAreCompatible().
4125 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4126 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4127 if (Old->hasInheritedPrototype())
4128 Old = Old->getCanonicalDecl();
4129 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4130 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4131 return true;
4132 }
4133
4134 // If we are merging two functions where only one of them has a prototype,
4135 // we may have enough information to decide to issue a diagnostic that the
4136 // function without a protoype will change behavior in C2x. This handles
4137 // cases like:
4138 // void i(); void i(int j);
4139 // void i(int j); void i();
4140 // void i(); void i(int j) {}
4141 // See ActOnFinishFunctionBody() for other cases of the behavior change
4142 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4143 // type without a prototype.
4144 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4145 !New->isImplicit() && !Old->isImplicit()) {
4146 const FunctionDecl *WithProto, *WithoutProto;
4147 if (New->hasWrittenPrototype()) {
4148 WithProto = New;
4149 WithoutProto = Old;
4150 } else {
4151 WithProto = Old;
4152 WithoutProto = New;
4153 }
4154
4155 if (WithProto->getNumParams() != 0) {
4156 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4157 // The one without the prototype will be changing behavior in C2x, so
4158 // warn about that one so long as it's a user-visible declaration.
4159 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4160 if (WithoutProto == New)
4161 IsWithoutProtoADef = NewDeclIsDefn;
4162 else
4163 IsWithProtoADef = NewDeclIsDefn;
4164 Diag(WithoutProto->getLocation(),
4165 diag::warn_non_prototype_changes_behavior)
4166 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4167 << (WithoutProto == Old) << IsWithProtoADef;
4168
4169 // The reason the one without the prototype will be changing behavior
4170 // is because of the one with the prototype, so note that so long as
4171 // it's a user-visible declaration. There is one exception to this:
4172 // when the new declaration is a definition without a prototype, the
4173 // old declaration with a prototype is not the cause of the issue,
4174 // and that does not need to be noted because the one with a
4175 // prototype will not change behavior in C2x.
4176 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4177 !IsWithoutProtoADef)
4178 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4179 }
4180 }
4181 }
4182
4183 if (Context.typesAreCompatible(OldQType, NewQType)) {
4184 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4185 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4186 const FunctionProtoType *OldProto = nullptr;
4187 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4188 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4189 // The old declaration provided a function prototype, but the
4190 // new declaration does not. Merge in the prototype.
4191 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4192 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4193 OldProto->getParamTypes(),
4194 OldProto->getExtProtoInfo());
4195 New->setType(NewQType);
4197
4198 // Synthesize parameters with the same types.
4200 for (const auto &ParamType : OldProto->param_types()) {
4202 Context, New, SourceLocation(), SourceLocation(), nullptr,
4203 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4204 Param->setScopeInfo(0, Params.size());
4205 Param->setImplicit();
4206 Params.push_back(Param);
4207 }
4208
4209 New->setParams(Params);
4210 }
4211
4212 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4213 }
4214 }
4215
4216 // Check if the function types are compatible when pointer size address
4217 // spaces are ignored.
4218 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4219 return false;
4220
4221 // GNU C permits a K&R definition to follow a prototype declaration
4222 // if the declared types of the parameters in the K&R definition
4223 // match the types in the prototype declaration, even when the
4224 // promoted types of the parameters from the K&R definition differ
4225 // from the types in the prototype. GCC then keeps the types from
4226 // the prototype.
4227 //
4228 // If a variadic prototype is followed by a non-variadic K&R definition,
4229 // the K&R definition becomes variadic. This is sort of an edge case, but
4230 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4231 // C99 6.9.1p8.
4232 if (!getLangOpts().CPlusPlus &&
4233 Old->hasPrototype() && !New->hasPrototype() &&
4234 New->getType()->getAs<FunctionProtoType>() &&
4235 Old->getNumParams() == New->getNumParams()) {
4238 const FunctionProtoType *OldProto
4239 = Old->getType()->getAs<FunctionProtoType>();
4240 const FunctionProtoType *NewProto
4241 = New->getType()->getAs<FunctionProtoType>();
4242
4243 // Determine whether this is the GNU C extension.
4244 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4245 NewProto->getReturnType());
4246 bool LooseCompatible = !MergedReturn.isNull();
4247 for (unsigned Idx = 0, End = Old->getNumParams();
4248 LooseCompatible && Idx != End; ++Idx) {
4249 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4250 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4251 if (Context.typesAreCompatible(OldParm->getType(),
4252 NewProto->getParamType(Idx))) {
4253 ArgTypes.push_back(NewParm->getType());
4254 } else if (Context.typesAreCompatible(OldParm->getType(),
4255 NewParm->getType(),
4256 /*CompareUnqualified=*/true)) {
4257 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4258 NewProto->getParamType(Idx) };
4259 Warnings.push_back(Warn);
4260 ArgTypes.push_back(NewParm->getType());
4261 } else
4262 LooseCompatible = false;
4263 }
4264
4265 if (LooseCompatible) {
4266 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4267 Diag(Warnings[Warn].NewParm->getLocation(),
4268 diag::ext_param_promoted_not_compatible_with_prototype)
4269 << Warnings[Warn].PromotedType
4270 << Warnings[Warn].OldParm->getType();
4271 if (Warnings[Warn].OldParm->getLocation().isValid())
4272 Diag(Warnings[Warn].OldParm->getLocation(),
4273 diag::note_previous_declaration);
4274 }
4275
4276 if (MergeTypeWithOld)
4277 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4278 OldProto->getExtProtoInfo()));
4279 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4280 }
4281
4282 // Fall through to diagnose conflicting types.
4283 }
4284
4285 // A function that has already been declared has been redeclared or
4286 // defined with a different type; show an appropriate diagnostic.
4287
4288 // If the previous declaration was an implicitly-generated builtin
4289 // declaration, then at the very least we should use a specialized note.
4290 unsigned BuiltinID;
4291 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4292 // If it's actually a library-defined builtin function like 'malloc'
4293 // or 'printf', just warn about the incompatible redeclaration.
4295 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4296 Diag(OldLocation, diag::note_previous_builtin_declaration)
4297 << Old << Old->getType();
4298 return false;
4299 }
4300
4301 PrevDiag = diag::note_previous_builtin_declaration;
4302 }
4303
4304 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4305 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4306 return true;
4307}
4308
4309/// Completes the merge of two function declarations that are
4310/// known to be compatible.
4311///
4312/// This routine handles the merging of attributes and other
4313/// properties of function declarations from the old declaration to
4314/// the new declaration, once we know that New is in fact a
4315/// redeclaration of Old.
4316///
4317/// \returns false
4319 Scope *S, bool MergeTypeWithOld) {
4320 // Merge the attributes
4321 mergeDeclAttributes(New, Old);
4322
4323 // Merge "pure" flag.
4324 if (Old->isPure())
4325 New->setPure();
4326
4327 // Merge "used" flag.
4328 if (Old->getMostRecentDecl()->isUsed(false))
4329 New->setIsUsed();
4330
4331 // Merge attributes from the parameters. These can mismatch with K&R
4332 // declarations.
4333 if (New->getNumParams() == Old->getNumParams())
4334 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4335 ParmVarDecl *NewParam = New->getParamDecl(i);
4336 ParmVarDecl *OldParam = Old->getParamDecl(i);
4337 mergeParamDeclAttributes(NewParam, OldParam, *this);
4338 mergeParamDeclTypes(NewParam, OldParam, *this);
4339 }
4340
4341 if (getLangOpts().CPlusPlus)
4342 return MergeCXXFunctionDecl(New, Old, S);
4343
4344 // Merge the function types so the we get the composite types for the return
4345 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4346 // was visible.
4347 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4348 if (!Merged.isNull() && MergeTypeWithOld)
4349 New->setType(Merged);
4350
4351 return false;
4352}
4353
4355 ObjCMethodDecl *oldMethod) {
4356 // Merge the attributes, including deprecated/unavailable
4357 AvailabilityMergeKind MergeKind =
4362 : AMK_Override;
4363
4364 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4365
4366 // Merge attributes from the parameters.
4368 oe = oldMethod->param_end();
4370 ni = newMethod->param_begin(), ne = newMethod->param_end();
4371 ni != ne && oi != oe; ++ni, ++oi)
4372 mergeParamDeclAttributes(*ni, *oi, *this);
4373
4374 CheckObjCMethodOverride(newMethod, oldMethod);
4375}
4376
4378 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4379
4381 ? diag::err_redefinition_different_type
4382 : diag::err_redeclaration_different_type)
4383 << New->getDeclName() << New->getType() << Old->getType();
4384
4385 diag::kind PrevDiag;
4386 SourceLocation OldLocation;
4387 std::tie(PrevDiag, OldLocation)
4389 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4390 New->setInvalidDecl();
4391}
4392
4393/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4394/// scope as a previous declaration 'Old'. Figure out how to merge their types,
4395/// emitting diagnostics as appropriate.
4396///
4397/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4398/// to here in AddInitializerToDecl. We can't check them before the initializer
4399/// is attached.
4401 bool MergeTypeWithOld) {
4402 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4403 return;
4404
4405 QualType MergedT;
4406 if (getLangOpts().CPlusPlus) {
4407 if (New->getType()->isUndeducedType()) {
4408 // We don't know what the new type is until the initializer is attached.
4409 return;
4410 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4411 // These could still be something that needs exception specs checked.
4412 return MergeVarDeclExceptionSpecs(New, Old);
4413 }
4414 // C++ [basic.link]p10:
4415 // [...] the types specified by all declarations referring to a given
4416 // object or function shall be identical, except that declarations for an
4417 // array object can specify array types that differ by the presence or
4418 // absence of a major array bound (8.3.4).
4419 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4420 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4421 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4422
4423 // We are merging a variable declaration New into Old. If it has an array
4424 // bound, and that bound differs from Old's bound, we should diagnose the
4425 // mismatch.
4426 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4427 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4428 PrevVD = PrevVD->getPreviousDecl()) {
4429 QualType PrevVDTy = PrevVD->getType();
4430 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4431 continue;
4432
4433 if (!Context.hasSameType(New->getType(), PrevVDTy))
4434 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4435 }
4436 }
4437
4438 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4439 if (Context.hasSameType(OldArray->getElementType(),
4440 NewArray->getElementType()))
4441 MergedT = New->getType();
4442 }
4443 // FIXME: Check visibility. New is hidden but has a complete type. If New
4444 // has no array bound, it should not inherit one from Old, if Old is not
4445 // visible.
4446 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4447 if (Context.hasSameType(OldArray->getElementType(),
4448 NewArray->getElementType()))
4449 MergedT = Old->getType();
4450 }
4451 }
4452 else if (New->getType()->isObjCObjectPointerType() &&
4453 Old->getType()->isObjCObjectPointerType()) {
4454 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4455 Old->getType());
4456 }
4457 } else {
4458 // C 6.2.7p2:
4459 // All declarations that refer to the same object or function shall have
4460 // compatible type.
4461 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4462 }
4463 if (MergedT.isNull()) {
4464 // It's OK if we couldn't merge types if either type is dependent, for a
4465 // block-scope variable. In other cases (static data members of class
4466 // templates, variable templates, ...), we require the types to be
4467 // equivalent.
4468 // FIXME: The C++ standard doesn't say anything about this.
4469 if ((New->getType()->isDependentType() ||
4470 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4471 // If the old type was dependent, we can't merge with it, so the new type
4472 // becomes dependent for now. We'll reproduce the original type when we
4473 // instantiate the TypeSourceInfo for the variable.
4474 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4476 return;
4477 }
4478 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4479 }
4480
4481 // Don't actually update the type on the new declaration if the old
4482 // declaration was an extern declaration in a different scope.
4483 if (MergeTypeWithOld)
4484 New->setType(MergedT);
4485}
4486
4487static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4489 // C11 6.2.7p4:
4490 // For an identifier with internal or external linkage declared
4491 // in a scope in which a prior declaration of that identifier is
4492 // visible, if the prior declaration specifies internal or
4493 // external linkage, the type of the identifier at the later
4494 // declaration becomes the composite type.
4495 //
4496 // If the variable isn't visible, we do not merge with its type.
4497 if (Previous.isShadowed())
4498 return false;
4499
4500 if (S.getLangOpts().CPlusPlus) {
4501 // C++11 [dcl.array]p3:
4502 // If there is a preceding declaration of the entity in the same
4503 // scope in which the bound was specified, an omitted array bound
4504 // is taken to be the same as in that earlier declaration.
4505 return NewVD->isPreviousDeclInSameBlockScope() ||
4508 } else {
4509 // If the old declaration was function-local, don't merge with its
4510 // type unless we're in the same function.
4511 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4512 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4513 }
4514}
4515
4516/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4517/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4518/// situation, merging decls or emitting diagnostics as appropriate.
4519///
4520/// Tentative definition rules (C99 6.9.2p2) are checked by
4521/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4522/// definitions here, since the initializer hasn't been attached.
4523///
4525 // If the new decl is already invalid, don't do any other checking.
4526 if (New->isInvalidDecl())
4527 return;
4528
4529 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4530 return;
4531
4532 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4533
4534 // Verify the old decl was also a variable or variable template.
4535 VarDecl *Old = nullptr;
4536 VarTemplateDecl *OldTemplate = nullptr;
4537 if (Previous.isSingleResult()) {
4538 if (NewTemplate) {
4539 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4540 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4541
4542 if (auto *Shadow =
4543 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4544 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4545 return New->setInvalidDecl();
4546 } else {
4547 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4548
4549 if (auto *Shadow =
4550 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4551 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4552 return New->setInvalidDecl();
4553 }
4554 }
4555 if (!Old) {
4556 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4557 << New->getDeclName();
4558 notePreviousDefinition(Previous.getRepresentativeDecl(),
4559 New->getLocation());
4560 return New->setInvalidDecl();
4561 }
4562
4563 // If the old declaration was found in an inline namespace and the new
4564 // declaration was qualified, update the DeclContext to match.
4566
4567 // Ensure the template parameters are compatible.
4568 if (NewTemplate &&
4570 OldTemplate->getTemplateParameters(),
4571 /*Complain=*/true, TPL_TemplateMatch))
4572 return New->setInvalidDecl();
4573
4574 // C++ [class.mem]p1:
4575 // A member shall not be declared twice in the member-specification [...]
4576 //
4577 // Here, we need only consider static data members.
4578 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4579 Diag(New->getLocation(), diag::err_duplicate_member)
4580 << New->getIdentifier();
4581 Diag(Old->getLocation(), diag::note_previous_declaration);
4582 New->setInvalidDecl();
4583 }
4584
4585 mergeDeclAttributes(New, Old);
4586 // Warn if an already-declared variable is made a weak_import in a subsequent
4587 // declaration
4588 if (New->hasAttr<WeakImportAttr>() &&
4589 Old->getStorageClass() == SC_None &&
4590 !Old->hasAttr<WeakImportAttr>()) {
4591 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4592 Diag(Old->getLocation(), diag::note_previous_declaration);
4593 // Remove weak_import attribute on new declaration.
4594 New->dropAttr<WeakImportAttr>();
4595 }
4596
4597 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4598 if (!Old->hasAttr<InternalLinkageAttr>()) {
4599 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4600 << ILA;
4601 Diag(Old->getLocation(), diag::note_previous_declaration);
4602 New->dropAttr<InternalLinkageAttr>();
4603 }
4604
4605 // Merge the types.
4606 VarDecl *MostRecent = Old->getMostRecentDecl();
4607 if (MostRecent != Old) {
4608 MergeVarDeclTypes(New, MostRecent,
4609 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4610 if (New->isInvalidDecl())
4611 return;
4612 }
4613
4614 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4615 if (New->isInvalidDecl())
4616 return;
4617
4618 diag::kind PrevDiag;
4619 SourceLocation OldLocation;
4620 std::tie(PrevDiag, OldLocation) =
4622
4623 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4624 if (New->getStorageClass() == SC_Static &&
4625 !New->isStaticDataMember() &&
4626 Old->hasExternalFormalLinkage()) {
4627 if (getLangOpts().MicrosoftExt) {
4628 Diag(New->getLocation(), diag::ext_static_non_static)
4629 << New->getDeclName();
4630 Diag(OldLocation, PrevDiag);
4631 } else {
4632 Diag(New->getLocation(), diag::err_static_non_static)
4633 << New->getDeclName();
4634 Diag(OldLocation, PrevDiag);
4635 return New->setInvalidDecl();
4636 }
4637 }
4638 // C99 6.2.2p4:
4639 // For an identifier declared with the storage-class specifier
4640 // extern in a scope in which a prior declaration of that
4641 // identifier is visible,23) if the prior declaration specifies
4642 // internal or external linkage, the linkage of the identifier at
4643 // the later declaration is the same as the linkage specified at
4644 // the prior declaration. If no prior declaration is visible, or
4645 // if the prior declaration specifies no linkage, then the
4646 // identifier has external linkage.
4647 if (New->hasExternalStorage() && Old->hasLinkage())
4648 /* Okay */;
4649 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4650 !New->isStaticDataMember() &&
4652 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4653 Diag(OldLocation, PrevDiag);
4654 return New->setInvalidDecl();
4655 }
4656
4657 // Check if extern is followed by non-extern and vice-versa.
4658 if (New->hasExternalStorage() &&
4659 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4660 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4661 Diag(OldLocation, PrevDiag);
4662 return New->setInvalidDecl();
4663 }
4664 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4665 !New->hasExternalStorage()) {
4666 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4667 Diag(OldLocation, PrevDiag);
4668 return New->setInvalidDecl();
4669 }
4670
4671 if (CheckRedeclarationInModule(New, Old))
4672 return;
4673
4674 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4675
4676 // FIXME: The test for external storage here seems wrong? We still
4677 // need to check for mismatches.
4678 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4679 // Don't complain about out-of-line definitions of static members.
4680 !(Old->getLexicalDeclContext()->isRecord() &&
4681 !New->getLexicalDeclContext()->isRecord())) {
4682 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4683 Diag(OldLocation, PrevDiag);
4684 return New->setInvalidDecl();
4685 }
4686
4687 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4688 if (VarDecl *Def = Old->getDefinition()) {
4689 // C++1z [dcl.fcn.spec]p4:
4690 // If the definition of a variable appears in a translation unit before
4691 // its first declaration as inline, the program is ill-formed.
4692 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4693 Diag(Def->getLocation(), diag::note_previous_definition);
4694 }
4695 }
4696
4697 // If this redeclaration makes the variable inline, we may need to add it to
4698 // UndefinedButUsed.
4699 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4701 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4702 SourceLocation()));
4703
4704 if (New->getTLSKind() != Old->getTLSKind()) {
4705 if (!Old->getTLSKind()) {
4706 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4707 Diag(OldLocation, PrevDiag);
4708 } else if (!New->getTLSKind()) {
4709 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4710 Diag(OldLocation, PrevDiag);
4711 } else {
4712 // Do not allow redeclaration to change the variable between requiring
4713 // static and dynamic initialization.
4714 // FIXME: GCC allows this, but uses the TLS keyword on the first
4715 // declaration to determine the kind. Do we need to be compatible here?
4716 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4717 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4718 Diag(OldLocation, PrevDiag);
4719 }
4720 }
4721
4722 // C++ doesn't have tentative definitions, so go right ahead and check here.
4723 if (getLangOpts().CPlusPlus) {
4724 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4725 Old->getCanonicalDecl()->isConstexpr()) {
4726 // This definition won't be a definition any more once it's been merged.
4727 Diag(New->getLocation(),
4728 diag::warn_deprecated_redundant_constexpr_static_def);
4730 VarDecl *Def = Old->getDefinition();
4731 if (Def && checkVarDeclRedefinition(Def, New))
4732 return;
4733 }
4734 }
4735
4736 if (haveIncompatibleLanguageLinkages(Old, New)) {
4737 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4738 Diag(OldLocation, PrevDiag);
4739 New->setInvalidDecl();
4740 return;
4741 }
4742
4743 // Merge "used" flag.
4744 if (Old->getMostRecentDecl()->isUsed(false))
4745 New->setIsUsed();
4746
4747 // Keep a chain of previous declarations.
4748 New->setPreviousDecl(Old);
4749 if (NewTemplate)
4750 NewTemplate->setPreviousDecl(OldTemplate);
4751
4752 // Inherit access appropriately.
4753 New->setAccess(Old->getAccess());
4754 if (NewTemplate)
4755 NewTemplate->setAccess(New->getAccess());
4756
4757 if (Old->isInline())
4758 New->setImplicitlyInline();
4759}
4760
4762 SourceManager &SrcMgr = getSourceManager();
4763 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4764 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4765 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4766 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4767 auto &HSI = PP.getHeaderSearchInfo();
4768 StringRef HdrFilename =
4769 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4770
4771 auto noteFromModuleOrInclude = [&](Module *Mod,
4772 SourceLocation IncLoc) -> bool {
4773 // Redefinition errors with modules are common with non modular mapped
4774 // headers, example: a non-modular header H in module A that also gets
4775 // included directly in a TU. Pointing twice to the same header/definition
4776 // is confusing, try to get better diagnostics when modules is on.
4777 if (IncLoc.isValid()) {
4778 if (Mod) {
4779 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4780 << HdrFilename.str() << Mod->getFullModuleName();
4781 if (!Mod->DefinitionLoc.isInvalid())
4782 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4783 << Mod->getFullModuleName();
4784 } else {
4785 Diag(IncLoc, diag::note_redefinition_include_same_file)
4786 << HdrFilename.str();
4787 }
4788 return true;
4789 }
4790
4791 return false;
4792 };
4793
4794 // Is it the same file and same offset? Provide more information on why
4795 // this leads to a redefinition error.
4796 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4797 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4798 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4799 bool EmittedDiag =
4800 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4801 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4802
4803 // If the header has no guards, emit a note suggesting one.
4804 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4805 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4806
4807 if (EmittedDiag)
4808 return;
4809 }
4810
4811 // Redefinition coming from different files or couldn't do better above.
4812 if (Old->getLocation().isValid())
4813 Diag(Old->getLocation(), diag::note_previous_definition);
4814}
4815
4816/// We've just determined that \p Old and \p New both appear to be definitions
4817/// of the same variable. Either diagnose or fix the problem.
4819 if (!hasVisibleDefinition(Old) &&
4820 (New->getFormalLinkage() == InternalLinkage ||
4821 New->isInline() ||
4822 isa<VarTemplateSpecializationDecl>(New) ||
4823 New->getDescribedVarTemplate() ||
4826 // The previous definition is hidden, and multiple definitions are
4827 // permitted (in separate TUs). Demote this to a declaration.
4829
4830 // Make the canonical definition visible.
4831 if (auto *OldTD = Old->getDescribedVarTemplate())
4834 return false;
4835 } else {
4836 Diag(New->getLocation(), diag::err_redefinition) << New;
4838 New->setInvalidDecl();
4839 return true;
4840 }
4841}
4842
4843/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4844/// no declarator (e.g. "struct foo;") is parsed.
4846 DeclSpec &DS,
4847 const ParsedAttributesView &DeclAttrs,
4848 RecordDecl *&AnonRecord) {
4850 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4851}
4852
4853// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4854// disambiguate entities defined in different scopes.
4855// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4856// compatibility.
4857// We will pick our mangling number depending on which version of MSVC is being
4858// targeted.
4859static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4861 ? S->getMSCurManglingNumber()
4862 : S->getMSLastManglingNumber();
4863}
4864
4865void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4866 if (!Context.getLangOpts().CPlusPlus)
4867 return;
4868
4869 if (isa<CXXRecordDecl>(Tag->getParent())) {
4870 // If this tag is the direct child of a class, number it if
4871 // it is anonymous.
4872 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4873 return;
4875 Context.getManglingNumberContext(Tag->getParent());
4877 Tag, MCtx.getManglingNumber(
4878 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4879 return;
4880 }
4881
4882 // If this tag isn't a direct child of a class, number it if it is local.
4884 Decl *ManglingContextDecl;
4885 std::tie(MCtx, ManglingContextDecl) =
4886 getCurrentMangleNumberContext(Tag->getDeclContext());
4887 if (MCtx) {
4889 Tag, MCtx->getManglingNumber(
4890 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4891 }
4892}
4893
4894namespace {
4895struct NonCLikeKind {
4896 enum {
4897 None,
4898 BaseClass,
4899 DefaultMemberInit,
4900 Lambda,
4901 Friend,
4902 OtherMember,
4903 Invalid,
4904 } Kind = None;
4905 SourceRange Range;
4906
4907 explicit operator bool() { return Kind != None; }
4908};
4909}
4910
4911/// Determine whether a class is C-like, according to the rules of C++
4912/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4913static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4914 if (RD->isInvalidDecl())
4915 return {NonCLikeKind::Invalid, {}};
4916
4917 // C++ [dcl.typedef]p9: [P1766R1]
4918 // An unnamed class with a typedef name for linkage purposes shall not
4919 //
4920 // -- have any base classes
4921 if (RD->getNumBases())
4922 return {NonCLikeKind::BaseClass,
4924 RD->bases_end()[-1].getEndLoc())};
4925 bool Invalid = false;
4926 for (Decl *D : RD->decls()) {
4927 // Don't complain about things we already diagnosed.
4928 if (D->isInvalidDecl()) {
4929 Invalid = true;
4930 continue;
4931 }
4932
4933 // -- have any [...] default member initializers
4934 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4935 if (FD->hasInClassInitializer()) {
4936 auto *Init = FD->getInClassInitializer();
4937 return {NonCLikeKind::DefaultMemberInit,
4938 Init ? Init->getSourceRange() : D->getSourceRange()};
4939 }
4940 continue;
4941 }
4942
4943 // FIXME: We don't allow friend declarations. This violates the wording of
4944 // P1766, but not the intent.
4945 if (isa<FriendDecl>(D))
4946 return {NonCLikeKind::Friend, D->getSourceRange()};
4947
4948 // -- declare any members other than non-static data members, member
4949 // enumerations, or member classes,
4950 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4951 isa<EnumDecl>(D))
4952 continue;
4953 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4954 if (!MemberRD) {
4955 if (D->isImplicit())
4956 continue;
4957 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4958 }
4959
4960 // -- contain a lambda-expression,
4961 if (MemberRD->isLambda())
4962 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4963
4964 // and all member classes shall also satisfy these requirements
4965 // (recursively).
4966 if (MemberRD->isThisDeclarationADefinition()) {
4967 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4968 return Kind;
4969 }
4970 }
4971
4972 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4973}
4974
4976 TypedefNameDecl *NewTD) {
4977 if (TagFromDeclSpec->isInvalidDecl())
4978 return;
4979
4980 // Do nothing if the tag already has a name for linkage purposes.
4981 if (TagFromDeclSpec->hasNameForLinkage())
4982 return;
4983
4984 // A well-formed anonymous tag must always be a TUK_Definition.
4985 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4986
4987 // The type must match the tag exactly; no qualifiers allowed.
4989 Context.getTagDeclType(TagFromDeclSpec))) {
4990 if (getLangOpts().CPlusPlus)
4991 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4992 return;
4993 }
4994
4995 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4996 // An unnamed class with a typedef name for linkage purposes shall [be
4997 // C-like].
4998 //
4999 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5000 // shouldn't happen, but there are constructs that the language rule doesn't
5001 // disallow for which we can't reasonably avoid computing linkage early.
5002 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5003 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5004 : NonCLikeKind();
5005 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5006 if (NonCLike || ChangesLinkage) {
5007 if (NonCLike.Kind == NonCLikeKind::Invalid)
5008 return;
5009
5010 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5011 if (ChangesLinkage) {
5012 // If the linkage changes, we can't accept this as an extension.
5013 if (NonCLike.Kind == NonCLikeKind::None)
5014 DiagID = diag::err_typedef_changes_linkage;
5015 else
5016 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5017 }
5018
5019 SourceLocation FixitLoc =
5020 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5021 llvm::SmallString<40> TextToInsert;
5022 TextToInsert += ' ';
5023 TextToInsert += NewTD->getIdentifier()->getName();
5024
5025 Diag(FixitLoc, DiagID)
5026 << isa<TypeAliasDecl>(NewTD)
5027 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5028 if (NonCLike.Kind != NonCLikeKind::None) {
5029 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5030 << NonCLike.Kind - 1 << NonCLike.Range;
5031 }
5032 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5033 << NewTD << isa<TypeAliasDecl>(NewTD);
5034
5035 if (ChangesLinkage)
5036 return;
5037 }
5038
5039 // Otherwise, set this as the anon-decl typedef for the tag.
5040 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5041}
5042
5043static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5045 switch (T) {
5047 return 0;
5049 return 1;
5051 return 2;
5053 return 3;
5054 case DeclSpec::TST_enum:
5055 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5056 if (ED->isScopedUsingClassTag())
5057 return 5;
5058 if (ED->isScoped())
5059 return 6;
5060 }
5061 return 4;
5062 default:
5063 llvm_unreachable("unexpected type specifier");
5064 }
5065}
5066/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5067/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5068/// parameters to cope with template friend declarations.
5070 DeclSpec &DS,
5071 const ParsedAttributesView &DeclAttrs,
5072 MultiTemplateParamsArg TemplateParams,
5073 bool IsExplicitInstantiation,
5074 RecordDecl *&AnonRecord) {
5075 Decl *TagD = nullptr;
5076 TagDecl *Tag = nullptr;
5082 TagD = DS.getRepAsDecl();
5083
5084 if (!TagD) // We probably had an error
5085 return nullptr;
5086
5087 // Note that the above type specs guarantee that the
5088 // type rep is a Decl, whereas in many of the others
5089 // it's a Type.
5090 if (isa<TagDecl>(TagD))
5091 Tag = cast<TagDecl>(TagD);
5092 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5093 Tag = CTD->getTemplatedDecl();
5094 }
5095
5096 if (Tag) {
5097 handleTagNumbering(Tag, S);
5098 Tag->setFreeStanding();
5099 if (Tag->isInvalidDecl())
5100 return Tag;
5101 }
5102
5103 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5104 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5105 // or incomplete types shall not be restrict-qualified."
5106 if (TypeQuals & DeclSpec::TQ_restrict)
5108 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5109 << DS.getSourceRange();
5110 }
5111
5112 if (DS.isInlineSpecified())
5113 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5114 << getLangOpts().CPlusPlus17;
5115
5116 if (DS.hasConstexprSpecifier()) {
5117 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5118 // and definitions of functions and variables.
5119 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5120 // the declaration of a function or function template
5121 if (Tag)
5122 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5124 << static_cast<int>(DS.getConstexprSpecifier());
5125 else
5126 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5127 << static_cast<int>(DS.getConstexprSpecifier());
5128 // Don't emit warnings after this error.
5129 return TagD;
5130 }
5131
5133
5134 if (DS.isFriendSpecified()) {
5135 // If we're dealing with a decl but not a TagDecl, assume that
5136 // whatever routines created it handled the friendship aspect.
5137 if (TagD && !Tag)
5138 return nullptr;
5139 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5140 }
5141
5142 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5143 bool IsExplicitSpecialization =
5144 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5145 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5146 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5147 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5148 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5149 // nested-name-specifier unless it is an explicit instantiation
5150 // or an explicit specialization.
5151 //
5152 // FIXME: We allow class template partial specializations here too, per the
5153 // obvious intent of DR1819.
5154 //
5155 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5156 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5158 return nullptr;
5159 }
5160
5161 // Track whether this decl-specifier declares anything.
5162 bool DeclaresAnything = true;
5163
5164 // Handle anonymous struct definitions.
5165 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5166 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5168 if (getLangOpts().CPlusPlus ||
5169 Record->getDeclContext()->isRecord()) {
5170 // If CurContext is a DeclContext that can contain statements,
5171 // RecursiveASTVisitor won't visit the decls that
5172 // BuildAnonymousStructOrUnion() will put into CurContext.
5173 // Also store them here so that they can be part of the
5174 // DeclStmt that gets created in this case.
5175 // FIXME: Also return the IndirectFieldDecls created by
5176 // BuildAnonymousStructOr union, for the same reason?
5178 AnonRecord = Record;
5179 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5181 }
5182
5183 DeclaresAnything = false;
5184 }
5185 }
5186
5187 // C11 6.7.2.1p2:
5188 // A struct-declaration that does not declare an anonymous structure or
5189 // anonymous union shall contain a struct-declarator-list.
5190 //
5191 // This rule also existed in C89 and C99; the grammar for struct-declaration
5192 // did not permit a struct-declaration without a struct-declarator-list.
5195 // Check for Microsoft C extension: anonymous struct/union member.
5196 // Handle 2 kinds of anonymous struct/union:
5197 // struct STRUCT;
5198 // union UNION;
5199 // and
5200 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5201 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5202 if ((Tag && Tag->getDeclName()) ||
5204 RecordDecl *Record = nullptr;
5205 if (Tag)
5206 Record = dyn_cast<RecordDecl>(Tag);
5207 else if (const RecordType *RT =
5209 Record = RT->getDecl();
5210 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5211 Record = UT->getDecl();
5212
5213 if (Record && getLangOpts().MicrosoftExt) {
5214 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5215 << Record->isUnion() << DS.getSourceRange();
5216 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5217 }
5218
5219 DeclaresAnything = false;
5220 }
5221 }
5222
5223 // Skip all the checks below if we have a type error.
5225 (TagD && TagD->isInvalidDecl()))
5226 return TagD;
5227
5228 if (getLangOpts().CPlusPlus &&
5230 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5231 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5232 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5233 DeclaresAnything = false;
5234
5235 if (!DS.isMissingDeclaratorOk()) {
5236 // Customize diagnostic for a typedef missing a name.
5238 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5239 << DS.getSourceRange();
5240 else
5241 DeclaresAnything = false;
5242 }
5243
5244 if (DS.isModulePrivateSpecified() &&
5245 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5246 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5247 << Tag->getTagKind()
5249
5251
5252 // C 6.7/2:
5253 // A declaration [...] shall declare at least a declarator [...], a tag,
5254 // or the members of an enumeration.
5255 // C++ [dcl.dcl]p3:
5256 // [If there are no declarators], and except for the declaration of an
5257 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5258 // names into the program, or shall redeclare a name introduced by a
5259 // previous declaration.
5260 if (!DeclaresAnything) {
5261 // In C, we allow this as a (popular) extension / bug. Don't bother
5262 // producing further diagnostics for redundant qualifiers after this.
5263 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5264 ? diag::err_no_declarators
5265 : diag::ext_no_declarators)
5266 << DS.getSourceRange();
5267 return TagD;
5268 }
5269
5270 // C++ [dcl.stc]p1:
5271 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5272 // init-declarator-list of the declaration shall not be empty.
5273 // C++ [dcl.fct.spec]p1:
5274 // If a cv-qualifier appears in a decl-specifier-seq, the
5275 // init-declarator-list of the declaration shall not be empty.
5276 //
5277 // Spurious qualifiers here appear to be valid in C.
5278 unsigned DiagID = diag::warn_standalone_specifier;
5279 if (getLangOpts().CPlusPlus)
5280 DiagID = diag::ext_standalone_specifier;
5281
5282 // Note that a linkage-specification sets a storage class, but
5283 // 'extern "C" struct foo;' is actually valid and not theoretically
5284 // useless.
5285 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5286 if (SCS == DeclSpec::SCS_mutable)
5287 // Since mutable is not a viable storage class specifier in C, there is
5288 // no reason to treat it as an extension. Instead, diagnose as an error.
5289 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5290 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5291 Diag(DS.getStorageClassSpecLoc(), DiagID)
5293 }
5294
5298 if (DS.getTypeQualifiers()) {
5300 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5302 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5303 // Restrict is covered above.
5305 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5307 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5308 }
5309
5310 // Warn about ignored type attributes, for example:
5311 // __attribute__((aligned)) struct A;
5312 // Attributes should be placed after tag to apply to type declaration.
5313 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5314 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5315 if (TypeSpecType == DeclSpec::TST_class ||
5316 TypeSpecType == DeclSpec::TST_struct ||
5317 TypeSpecType == DeclSpec::TST_interface ||
5318 TypeSpecType == DeclSpec::TST_union ||
5319 TypeSpecType == DeclSpec::TST_enum) {
5320 for (const ParsedAttr &AL : DS.getAttributes())
5321 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5322 ? diag::err_declspec_keyword_has_no_effect
5323 : diag::warn_declspec_attribute_ignored)
5324 << AL << GetDiagnosticTypeSpecifierID(DS);
5325 for (const ParsedAttr &AL : DeclAttrs)
5326 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
5327 ? diag::err_declspec_keyword_has_no_effect
5328 : diag::warn_declspec_attribute_ignored)
5329 << AL << GetDiagnosticTypeSpecifierID(DS);
5330 }
5331 }
5332
5333 return TagD;
5334}
5335
5336/// We are trying to inject an anonymous member into the given scope;
5337/// check if there's an existing declaration that can't be overloaded.
5338///
5339/// \return true if this is a forbidden redeclaration
5341 Scope *S,
5342 DeclContext *Owner,
5343 DeclarationName Name,
5344 SourceLocation NameLoc,
5345 bool IsUnion) {
5346 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5348 if (!SemaRef.LookupName(R, S)) return false;
5349
5350 // Pick a representative declaration.
5352 assert(PrevDecl && "Expected a non-null Decl");
5353
5354 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5355 return false;
5356
5357 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5358 << IsUnion << Name;
5359 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5360
5361 return true;
5362}
5363
5364/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5365/// anonymous struct or union AnonRecord into the owning context Owner
5366/// and scope S. This routine will be invoked just after we realize
5367/// that an unnamed union or struct is actually an anonymous union or
5368/// struct, e.g.,
5369///
5370/// @code
5371/// union {
5372/// int i;
5373/// float f;
5374/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5375/// // f into the surrounding scope.x
5376/// @endcode
5377///
5378/// This routine is recursive, injecting the names of nested anonymous
5379/// structs/unions into the owning context and scope as well.
5380static bool
5382 RecordDecl *AnonRecord, AccessSpecifier AS,
5383 SmallVectorImpl<NamedDecl *> &Chaining) {
5384 bool Invalid = false;
5385
5386 // Look every FieldDecl and IndirectFieldDecl with a name.
5387 for (auto *D : AnonRecord->decls()) {
5388 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5389 cast<NamedDecl>(D)->getDeclName()) {
5390 ValueDecl *VD = cast<ValueDecl>(D);
5391 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5392 VD->getLocation(),
5393 AnonRecord->isUnion())) {
5394 // C++ [class.union]p2:
5395 // The names of the members of an anonymous union shall be
5396 // distinct from the names of any other entity in the
5397 // scope in which the anonymous union is declared.
5398 Invalid = true;
5399 } else {
5400 // C++ [class.union]p2:
5401 // For the purpose of name lookup, after the anonymous union
5402 // definition, the members of the anonymous union are
5403 // considered to have been defined in the scope in which the
5404 // anonymous union is declared.
5405 unsigned OldChainingSize = Chaining.size();
5406 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5407 Chaining.append(IF->chain_begin(), IF->chain_end());
5408 else
5409 Chaining.push_back(VD);
5410
5411 assert(Chaining.size() >= 2);
5412 NamedDecl **NamedChain =
5413 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5414 for (unsigned i = 0; i < Chaining.size(); i++)
5415 NamedChain[i] = Chaining[i];
5416
5418 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5419 VD->getType(), {NamedChain, Chaining.size()});
5420
5421 for (const auto *Attr : VD->attrs())
5422 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5423
5424 IndirectField->setAccess(AS);
5425 IndirectField->setImplicit();
5426 SemaRef.PushOnScopeChains(IndirectField, S);
5427
5428 // That includes picking up the appropriate access specifier.
5429 if (AS != AS_none) IndirectField->setAccess(AS);
5430
5431 Chaining.resize(OldChainingSize);
5432 }
5433 }
5434 }
5435
5436 return Invalid;
5437}
5438
5439/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5440/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5441/// illegal input values are mapped to SC_None.
5442static StorageClass
5444 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5445 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5446 "Parser allowed 'typedef' as storage class VarDecl.");
5447 switch (StorageClassSpec) {
5450 if (DS.isExternInLinkageSpec())
5451 return SC_None;
5452 return SC_Extern;
5453 case DeclSpec::SCS_static: return SC_Static;
5454 case DeclSpec::SCS_auto: return SC_Auto;
5457 // Illegal SCSs map to None: error reporting is up to the caller.
5458 case DeclSpec::SCS_mutable: // Fall through.
5459 case DeclSpec::SCS_typedef: return SC_None;
5460 }
5461 llvm_unreachable("unknown storage class specifier");
5462}
5463
5465 assert(Record->hasInClassInitializer());
5466
5467 for (const auto *I : Record->decls()) {
5468 const auto *FD = dyn_cast<FieldDecl>(I);
5469 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5470 FD = IFD->getAnonField();
5471 if (FD && FD->hasInClassInitializer())
5472 return FD->getLocation();
5473 }
5474
5475 llvm_unreachable("couldn't find in-class initializer");
5476}
5477
5479 SourceLocation DefaultInitLoc) {
5480 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5481 return;
5482
5483 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5484 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5485}
5486
5488 CXXRecordDecl *AnonUnion) {
5489 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5490 return;
5491
5493}
5494
5495/// BuildAnonymousStructOrUnion - Handle the declaration of an
5496/// anonymous structure or union. Anonymous unions are a C++ feature
5497/// (C++ [class.union]) and a C11 feature; anonymous structures
5498/// are a C11 feature and GNU C++ extension.
5500 AccessSpecifier AS,
5501 RecordDecl *Record,
5502 const PrintingPolicy &Policy) {
5503 DeclContext *Owner = Record->getDeclContext();
5504
5505 // Diagnose whether this anonymous struct/union is an extension.
5506 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5507 Diag(Record->getLocation(), diag::ext_anonymous_union);
5508 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5509 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5510 else if (!Record->isUnion() && !getLangOpts().C11)
5511 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5512
5513 // C and C++ require different kinds of checks for anonymous
5514 // structs/unions.
5515 bool Invalid = false;
5516 if (getLangOpts().CPlusPlus) {
5517 const char *PrevSpec = nullptr;
5518 if (Record->isUnion()) {
5519 // C++ [class.union]p6:
5520 // C++17 [class.union.anon]p2:
5521 // Anonymous unions declared in a named namespace or in the
5522 // global namespace shall be declared static.
5523 unsigned DiagID;
5524 DeclContext *OwnerScope = Owner->getRedeclContext();
5526 (OwnerScope->isTranslationUnit() ||
5527 (OwnerScope->isNamespace() &&
5528 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5529 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5530 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5531
5532 // Recover by adding 'static'.
5534 PrevSpec, DiagID, Policy);
5535 }
5536 // C++ [class.union]p6:
5537 // A storage class is not allowed in a declaration of an
5538 // anonymous union in a class scope.
5540 isa<RecordDecl>(Owner)) {
5542 diag::err_anonymous_union_with_storage_spec)
5544
5545 // Recover by removing the storage specifier.
5548 PrevSpec, DiagID, Context.getPrintingPolicy());
5549 }
5550 }
5551
5552 // Ignore const/volatile/restrict qualifiers.
5553 if (DS.getTypeQualifiers()) {
5555 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5556 << Record->isUnion() << "const"
5560 diag::ext_anonymous_struct_union_qualified)
5561 << Record->isUnion() << "volatile"
5565 diag::ext_anonymous_struct_union_qualified)
5566 << Record->isUnion() << "restrict"
5570 diag::ext_anonymous_struct_union_qualified)
5571 << Record->isUnion() << "_Atomic"
5575 diag::ext_anonymous_struct_union_qualified)
5576 << Record->isUnion() << "__unaligned"
5578
5580 }
5581
5582 // C++ [class.union]p2:
5583 // The member-specification of an anonymous union shall only
5584 // define non-static data members. [Note: nested types and
5585 // functions cannot be declared within an anonymous union. ]
5586 for (auto *Mem : Record->decls()) {
5587 // Ignore invalid declarations; we already diagnosed them.
5588 if (Mem->isInvalidDecl())
5589 continue;
5590
5591 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5592 // C++ [class.union]p3:
5593 // An anonymous union shall not have private or protected
5594 // members (clause 11).
5595 assert(FD->getAccess() != AS_none);
5596 if (FD->getAccess() != AS_public) {
5597 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5598 << Record->isUnion() << (FD->getAccess() == AS_protected);
5599 Invalid = true;
5600 }
5601
5602 // C++ [class.union]p1
5603 // An object of a class with a non-trivial constructor, a non-trivial
5604 // copy constructor, a non-trivial destructor, or a non-trivial copy
5605 // assignment operator cannot be a member of a union, nor can an
5606 // array of such objects.
5607 if (CheckNontrivialField(FD))
5608 Invalid = true;
5609 } else if (Mem->isImplicit()) {
5610 // Any implicit members are fine.
5611 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5612 // This is a type that showed up in an
5613 // elaborated-type-specifier inside the anonymous struct or
5614 // union, but which actually declares a type outside of the
5615 // anonymous struct or union. It's okay.
5616 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5617 if (!MemRecord->isAnonymousStructOrUnion() &&
5618 MemRecord->getDeclName()) {
5619 // Visual C++ allows type definition in anonymous struct or union.
5620 if (getLangOpts().MicrosoftExt)
5621 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5622 << Record->isUnion();
5623 else {
5624 // This is a nested type declaration.
5625 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5626 << Record->isUnion();
5627 Invalid = true;
5628 }
5629 } else {
5630 // This is an anonymous type definition within another anonymous type.
5631 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5632 // not part of standard C++.
5633 Diag(MemRecord->getLocation(),
5634 diag::ext_anonymous_record_with_anonymous_type)
5635 << Record->isUnion();
5636 }
5637 } else if (isa<AccessSpecDecl>(Mem)) {
5638 // Any access specifier is fine.
5639 } else if (isa<StaticAssertDecl>(Mem)) {
5640 // In C++1z, static_assert declarations are also fine.
5641 } else {
5642 // We have something that isn't a non-static data
5643 // member. Complain about it.
5644 unsigned DK = diag::err_anonymous_record_bad_member;
5645 if (isa<TypeDecl>(Mem))
5646 DK = diag::err_anonymous_record_with_type;
5647 else if (isa<FunctionDecl>(Mem))
5648 DK = diag::err_anonymous_record_with_function;
5649 else if (isa<VarDecl>(Mem))
5650 DK = diag::err_anonymous_record_with_static;
5651
5652 // Visual C++ allows type definition in anonymous struct or union.
5653 if (getLangOpts().MicrosoftExt &&
5654 DK == diag::err_anonymous_record_with_type)
5655 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5656 << Record->isUnion();
5657 else {
5658 Diag(Mem->getLocation(), DK) << Record->isUnion();
5659 Invalid = true;
5660 }
5661 }
5662 }
5663
5664 // C++11 [class.union]p8 (DR1460):
5665 // At most one variant member of a union may have a
5666 // brace-or-equal-initializer.
5667 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5668 Owner->isRecord())
5669 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5670 cast<CXXRecordDecl>(Record));
5671 }
5672
5673 if (!Record->isUnion() && !Owner->isRecord()) {
5674 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5675 << getLangOpts().CPlusPlus;
5676 Invalid = true;
5677 }
5678
5679 // C++ [dcl.dcl]p3:
5680 // [If there are no declarators], and except for the declaration of an
5681 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5682 // names into the program
5683 // C++ [class.mem]p2:
5684 // each such member-declaration shall either declare at least one member
5685 // name of the class or declare at least one unnamed bit-field
5686 //
5687 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5688 if (getLangOpts().CPlusPlus && Record->field_empty())
5689 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5690
5691 // Mock up a declarator.
5693 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5694 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5695
5696 // Create a declaration for this anonymous struct/union.
5697 NamedDecl *Anon = nullptr;
5698 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5699 Anon = FieldDecl::Create(
5700 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5701 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5702 /*BitWidth=*/nullptr, /*Mutable=*/false,
5703 /*InitStyle=*/ICIS_NoInit);
5704 Anon->setAccess(AS);
5705 ProcessDeclAttributes(S, Anon, Dc);
5706
5707 if (getLangOpts().CPlusPlus)
5708 FieldCollector->Add(cast<FieldDecl>(Anon));
5709 } else {
5710 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5712 if (SCSpec == DeclSpec::SCS_mutable) {
5713 // mutable can only appear on non-static class members, so it's always
5714 // an error here
5715 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5716 Invalid = true;
5717 SC = SC_None;
5718 }
5719
5720 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5721 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5722 Context.getTypeDeclType(Record), TInfo, SC);
5723 ProcessDeclAttributes(S, Anon, Dc);
5724
5725 // Default-initialize the implicit variable. This initialization will be
5726 // trivial in almost all cases, except if a union member has an in-class
5727 // initializer:
5728 // union { int n = 0; };
5730 }
5731 Anon->setImplicit();
5732
5733 // Mark this as an anonymous struct/union type.
5734 Record->setAnonymousStructOrUnion(true);
5735
5736 // Add the anonymous struct/union object to the current
5737 // context. We'll be referencing this object when we refer to one of
5738 // its members.
5739 Owner->addDecl(Anon);
5740
5741 // Inject the members of the anonymous struct/union into the owning
5742 // context and into the identifier resolver chain for name lookup
5743 // purposes.
5745 Chain.push_back(Anon);
5746
5747 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5748 Invalid = true;
5749
5750 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5751 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5753 Decl *ManglingContextDecl;
5754 std::tie(MCtx, ManglingContextDecl) =
5755 getCurrentMangleNumberContext(NewVD->getDeclContext());
5756 if (MCtx) {
5758 NewVD, MCtx->getManglingNumber(
5759 NewVD, getMSManglingNumber(getLangOpts(), S)));
5761 }
5762 }
5763 }
5764
5765 if (Invalid)
5766 Anon->setInvalidDecl();
5767
5768 return Anon;
5769}
5770
5771/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5772/// Microsoft C anonymous structure.
5773/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5774/// Example:
5775///
5776/// struct A { int a; };
5777/// struct B { struct A; int b; };
5778///
5779/// void foo() {
5780/// B var;
5781/// var.a = 3;
5782/// }
5783///
5785 RecordDecl *Record) {
5786 assert(Record && "expected a record!");
5787
5788 // Mock up a declarator.
5790 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5791 assert(TInfo && "couldn't build declarator info for anonymous struct");
5792
5793 auto *ParentDecl = cast<RecordDecl>(CurContext);
5794 QualType RecTy = Context.getTypeDeclType(Record);
5795
5796 // Create a declaration for this anonymous struct.
5797 NamedDecl *Anon =
5798 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5799 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5800 /*BitWidth=*/nullptr, /*Mutable=*/false,
5801 /*InitStyle=*/ICIS_NoInit);
5802 Anon->setImplicit();
5803
5804 // Add the anonymous struct object to the current context.
5805 CurContext->addDecl(Anon);
5806
5807 // Inject the members of the anonymous struct into the current
5808 // context and into the identifier resolver chain for name lookup
5809 // purposes.
5811 Chain.push_back(Anon);
5812
5813 RecordDecl *RecordDef = Record->getDefinition();
5814 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5815 diag::err_field_incomplete_or_sizeless) ||
5817 AS_none, Chain)) {
5818 Anon->setInvalidDecl();
5819 ParentDecl->setInvalidDecl();
5820 }
5821
5822 return Anon;
5823}
5824
5825/// GetNameForDeclarator - Determine the full declaration name for the
5826/// given Declarator.
5830
5831/// Retrieves the declaration name from a parsed unqualified-id.
5834 DeclarationNameInfo NameInfo;
5835 NameInfo.setLoc(Name.StartLocation);
5836
5837 switch (Name.getKind()) {
5838
5841 NameInfo.setName(Name.Identifier);
5842 return NameInfo;
5843
5845 // C++ [temp.deduct.guide]p3:
5846 // The simple-template-id shall name a class template specialization.
5847 // The template-name shall be the same identifier as the template-name
5848 // of the simple-template-id.
5849 // These together intend to imply that the template-name shall name a
5850 // class template.
5851 // FIXME: template<typename T> struct X {};
5852 // template<typename T> using Y = X<T>;
5853 // Y(int) -> Y<int>;
5854 // satisfies these rules but does not name a class template.
5855 TemplateName TN = Name.TemplateName.get().get();
5856 auto *Template = TN.getAsTemplateDecl();
5857 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5858 Diag(Name.StartLocation,
5859 diag::err_deduction_guide_name_not_class_template)
5861 if (Template)
5862 Diag(Template->getLocation(), diag::note_template_decl_here);
5863 return DeclarationNameInfo();
5864 }
5865
5866 NameInfo.setName(
5868 return NameInfo;
5869 }
5870
5873 Name.OperatorFunctionId.Operator));
5875 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5876 return NameInfo;
5877
5880 Name.Identifier));
5881 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5882 return NameInfo;
5883
5885 TypeSourceInfo *TInfo;
5886 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5887 if (Ty.isNull())
5888 return DeclarationNameInfo();
5891 NameInfo.setNamedTypeInfo(TInfo);
5892 return NameInfo;
5893 }
5894
5896 TypeSourceInfo *TInfo;
5897 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5898 if (Ty.isNull())
5899 return DeclarationNameInfo();
5902 NameInfo.setNamedTypeInfo(TInfo);
5903 return NameInfo;
5904 }
5905
5907 // In well-formed code, we can only have a constructor
5908 // template-id that refers to the current context, so go there
5909 // to find the actual type being constructed.
5910 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5911 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5912 return DeclarationNameInfo();
5913
5914 // Determine the type of the class being constructed.
5915 QualType CurClassType = Context.getTypeDeclType(CurClass);
5916
5917 // FIXME: Check two things: that the template-id names the same type as
5918 // CurClassType, and that the template-id does not occur when the name
5919 // was qualified.
5920
5922 Context.getCanonicalType(CurClassType)));
5923 // FIXME: should we retrieve TypeSourceInfo?
5924 NameInfo.setNamedTypeInfo(nullptr);
5925 return NameInfo;
5926 }
5927
5929 TypeSourceInfo *TInfo;
5930 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5931 if (Ty.isNull())
5932 return DeclarationNameInfo();
5935 NameInfo.setNamedTypeInfo(TInfo);
5936 return NameInfo;
5937 }
5938
5940 TemplateName TName = Name.TemplateId->Template.get();
5941 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5942 return Context.getNameForTemplate(TName, TNameLoc);
5943 }
5944
5945 } // switch (Name.getKind())
5946
5947 llvm_unreachable("Unknown name kind");
5948}
5949
5951 do {
5952 if (Ty->isPointerType() || Ty->isReferenceType())
5953 Ty = Ty->getPointeeType();
5954 else if (Ty->isArrayType())
5956 else
5957 return Ty.withoutLocalFastQualifiers();
5958 } while (true);
5959}
5960
5961/// hasSimilarParameters - Determine whether the C++ functions Declaration
5962/// and Definition have "nearly" matching parameters. This heuristic is
5963/// used to improve diagnostics in the case where an out-of-line function
5964/// definition doesn't match any declaration within the class or namespace.
5965/// Also sets Params to the list of indices to the parameters that differ
5966/// between the declaration and the definition. If hasSimilarParameters
5967/// returns true and Params is empty, then all of the parameters match.
5971 SmallVectorImpl<unsigned> &Params) {
5972 Params.clear();
5973 if (Declaration->param_size() != Definition->param_size())
5974 return false;
5975 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5976 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5977 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5978
5979 // The parameter types are identical
5980 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5981 continue;
5982
5983 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5984 QualType DefParamBaseTy = getCoreType(DefParamTy);
5985 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5986 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5987
5988 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5989 (DeclTyName && DeclTyName == DefTyName))
5990 Params.push_back(Idx);
5991 else // The two parameters aren't even close
5992 return false;
5993 }
5994
5995 return true;
5996}
5997
5998/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5999/// declarator needs to be rebuilt in the current instantiation.
6000/// Any bits of declarator which appear before the name are valid for
6001/// consideration here. That's specifically the type in the decl spec
6002/// and the base type in any member-pointer chunks.
6004 DeclarationName Name) {
6005 // The types we specifically need to rebuild are:
6006 // - typenames, typeofs, and decltypes
6007 // - types which will become injected class names
6008 // Of course, we also need to rebuild any type referencing such a
6009 // type. It's safest to just say "dependent", but we call out a
6010 // few cases here.
6011
6012 DeclSpec &DS = D.getMutableDeclSpec();
6013 switch (DS.getTypeSpecType()) {
6017#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6018#include "clang/Basic/TransformTypeTraits.def"
6019 case DeclSpec::TST_atomic: {
6020 // Grab the type from the parser.
6021 TypeSourceInfo *TSI = nullptr;
6022 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6023 if (T.isNull() || !T->isInstantiationDependentType()) break;
6024
6025 // Make sure there's a type source info. This isn't really much
6026 // of a waste; most dependent types should have type source info
6027 // attached already.
6028 if (!TSI)
6030
6031 // Rebuild the type in the current instantiation.
6033 if (!TSI) return true;
6034
6035 // Store the new type back in the decl spec.
6036 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6037 DS.UpdateTypeRep(LocType);
6038 break;
6039 }
6040
6044 Expr *E = DS.getRepAsExpr();
6046 if (Result.isInvalid()) return true;
6047 DS.UpdateExprRep(Result.get());
6048 break;
6049 }
6050
6051 default:
6052 // Nothing to do for these decl specs.
6053 break;
6054 }
6055
6056 // It doesn't matter what order we do this in.
6057 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6058 DeclaratorChunk &Chunk = D.getTypeObject(I);
6059
6060 // The only type information in the declarator which can come
6061 // before the declaration name is the base type of a member
6062 // pointer.
6064 continue;
6065
6066 // Rebuild the scope specifier in-place.
6067 CXXScopeSpec &SS = Chunk.Mem.Scope();
6069 return true;
6070 }
6071
6072 return false;
6073}
6074
6075/// Returns true if the declaration is declared in a system header or from a
6076/// system macro.
6077static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6078 return SM.isInSystemHeader(D->getLocation()) ||
6079 SM.isInSystemMacro(D->getLocation());
6080}
6081
6083 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6084 // of system decl.
6085 if (D->getPreviousDecl() || D->isImplicit())
6086 return;
6090 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6091 << D << static_cast<int>(Status);
6092 }
6093}
6094
6097
6098 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6099 // declaration only if the `bind_to_declaration` extension is set.
6102 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6103 implementation_extension_bind_to_declaration))
6105 S, D, MultiTemplateParamsArg(), Bases);
6106
6108
6110 Dcl && Dcl->getDeclContext()->isFileContext())
6112
6113 if (!Bases.empty())
6115
6116 return Dcl;
6117}
6118
6119/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6120/// If T is the name of a class, then each of the following shall have a
6121/// name different from T:
6122/// - every static data member of class T;
6123/// - every member function of class T
6124/// - every member of class T that is itself a type;
6125/// \returns true if the declaration name violates these rules.
6127 DeclarationNameInfo NameInfo) {
6128 DeclarationName Name = NameInfo.getName();
6129
6130 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6131 while (Record && Record->isAnonymousStructOrUnion())
6132 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6133 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6134 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6135 return true;
6136 }
6137
6138 return false;
6139}
6140
6141/// Diagnose a declaration whose declarator-id has the given
6142/// nested-name-specifier.
6143///
6144/// \param SS The nested-name-specifier of the declarator-id.
6145///
6146/// \param DC The declaration context to which the nested-name-specifier
6147/// resolves.
6148///
6149/// \param Name The name of the entity being declared.
6150///
6151/// \param Loc The location of the name of the entity being declared.
6152///
6153/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6154/// we're declaring an explicit / partial specialization / instantiation.
6155///
6156/// \returns true if we cannot safely recover from this error, false otherwise.
6158 DeclarationName Name,
6159 SourceLocation Loc, bool IsTemplateId) {
6160 DeclContext *Cur = CurContext;
6161 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6162 Cur = Cur->getParent();
6163
6164 // If the user provided a superfluous scope specifier that refers back to the
6165 // class in which the entity is already declared, diagnose and ignore it.
6166 //
6167 // class X {
6168 // void X::f();
6169 // };
6170 //
6171 // Note, it was once ill-formed to give redundant qualification in all
6172 // contexts, but that rule was removed by DR482.
6173 if (Cur->Equals(DC)) {
6174 if (Cur->isRecord()) {
6175 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6176 : diag::err_member_extra_qualification)
6177 << Name << FixItHint::CreateRemoval(SS.getRange());
6178 SS.clear();
6179 } else {
6180 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6181 }
6182 return false;
6183 }
6184
6185 // Check whether the qualifying scope encloses the scope of the original
6186 // declaration. For a template-id, we perform the checks in
6187 // CheckTemplateSpecializationScope.
6188 if (!Cur->Encloses(DC) && !IsTemplateId) {
6189 if (Cur->isRecord())
6190 Diag(Loc, diag::err_member_qualification)
6191 << Name << SS.getRange();
6192 else if (isa<TranslationUnitDecl>(DC))
6193 Diag(Loc, diag::err_invalid_declarator_global_scope)
6194 << Name << SS.getRange();
6195 else if (isa<FunctionDecl>(Cur))
6196 Diag(Loc, diag::err_invalid_declarator_in_function)
6197 << Name << SS.getRange();
6198 else if (isa<BlockDecl>(Cur))
6199 Diag(Loc, diag::err_invalid_declarator_in_block)
6200 << Name << SS.getRange();
6201 else if (isa<ExportDecl>(Cur)) {
6202 if (!isa<NamespaceDecl>(DC))
6203 Diag(Loc, diag::err_export_non_namespace_scope_name)
6204 << Name << SS.getRange();
6205 else
6206 // The cases that DC is not NamespaceDecl should be handled in
6207 // CheckRedeclarationExported.
6208 return false;
6209 } else
6210 Diag(Loc, diag::err_invalid_declarator_scope)
6211 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6212
6213 return true;
6214 }
6215
6216 if (Cur->isRecord()) {
6217 // Cannot qualify members within a class.
6218 Diag(Loc, diag::err_member_qualification)
6219 << Name << SS.getRange();
6220 SS.clear();
6221
6222 // C++ constructors and destructors with incorrect scopes can break
6223 // our AST invariants by having the wrong underlying types. If
6224 // that's the case, then drop this declaration entirely.
6225 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6226 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6227 !Context.hasSameType(Name.getCXXNameType(),
6228 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6229 return true;
6230
6231 return false;
6232 }
6233
6234 // C++11 [dcl.meaning]p1:
6235 // [...] "The nested-name-specifier of the qualified declarator-id shall
6236 // not begin with a decltype-specifer"
6238 while (SpecLoc.getPrefix())
6239 SpecLoc = SpecLoc.getPrefix();
6240 if (isa_and_nonnull<DecltypeType>(
6241 SpecLoc.getNestedNameSpecifier()->getAsType()))
6242 Diag(Loc, diag::err_decltype_in_declarator)
6243 << SpecLoc.getTypeLoc().getSourceRange();
6244
6245 return false;
6246}
6247
6249 MultiTemplateParamsArg TemplateParamLists) {
6250 // TODO: consider using NameInfo for diagnostic.
6252 DeclarationName Name = NameInfo.getName();
6253
6254 // All of these full declarators require an identifier. If it doesn't have
6255 // one, the ParsedFreeStandingDeclSpec action should be used.
6256 if (D.isDecompositionDeclarator()) {
6257 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6258 } else if (!Name) {
6259 if (!D.isInvalidType()) // Reject this if we think it is valid.
6260 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6262 return nullptr;
6264 return nullptr;
6265
6266 // The scope passed in may not be a decl scope. Zip up the scope tree until
6267 // we find one that is.
6268 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6269 (S->getFlags() & Scope::TemplateParamScope) != 0)
6270 S = S->getParent();
6271
6272 DeclContext *DC = CurContext;
6273 if (D.getCXXScopeSpec().isInvalid())
6274 D.setInvalidType();
6275 else if (D.getCXXScopeSpec().isSet()) {
6278 return nullptr;
6279
6280 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6281 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6282 if (!DC || isa<EnumDecl>(DC)) {
6283 // If we could not compute the declaration context, it's because the
6284 // declaration context is dependent but does not refer to a class,
6285 // class template, or class template partial specialization. Complain
6286 // and return early, to avoid the coming semantic disaster.
6288 diag::err_template_qualified_declarator_no_match)
6290 << D.getCXXScopeSpec().getRange();
6291 return nullptr;
6292 }
6293 bool IsDependentContext = DC->isDependentContext();
6294
6295 if (!IsDependentContext &&
6297 return nullptr;
6298
6299 // If a class is incomplete, do not parse entities inside it.
6300 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6302 diag::err_member_def_undefined_record)
6303 << Name << DC << D.getCXXScopeSpec().getRange();
6304 return nullptr;
6305 }
6306 if (!D.getDeclSpec().isFriendSpecified()) {
6308 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6310 if (DC->isRecord())
6311 return nullptr;
6312
6313 D.setInvalidType();
6314 }
6315 }
6316
6317 // Check whether we need to rebuild the type of the given
6318 // declaration in the current instantiation.
6319 if (EnteringContext && IsDependentContext &&
6320 TemplateParamLists.size() != 0) {
6321 ContextRAII SavedContext(*this, DC);
6322 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6323 D.setInvalidType();
6324 }
6325 }
6326
6327 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6328 QualType R = TInfo->getType();
6329
6332 D.setInvalidType();
6333
6334 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6336
6337 // See if this is a redefinition of a variable in the same scope.
6338 if (!D.getCXXScopeSpec().isSet()) {
6339 bool IsLinkageLookup = false;
6340 bool CreateBuiltins = false;
6341
6342 // If the declaration we're planning to build will be a function
6343 // or object with linkage, then look for another declaration with
6344 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6345 //
6346 // If the declaration we're planning to build will be declared with
6347 // external linkage in the translation unit, create any builtin with
6348 // the same name.
6350 /* Do nothing*/;
6351 else if (CurContext->isFunctionOrMethod() &&
6353 R->isFunctionType())) {
6354 IsLinkageLookup = true;
6355 CreateBuiltins =
6359 CreateBuiltins = true;
6360
6361 if (IsLinkageLookup) {
6363 Previous.setRedeclarationKind(ForExternalRedeclaration);
6364 }
6365
6366 LookupName(Previous, S, CreateBuiltins);
6367 } else { // Something like "int foo::x;"
6369
6370 // C++ [dcl.meaning]p1:
6371 // When the declarator-id is qualified, the declaration shall refer to a
6372 // previously declared member of the class or namespace to which the
6373 // qualifier refers (or, in the case of a namespace, of an element of the
6374 // inline namespace set of that namespace (7.3.1)) or to a specialization
6375 // thereof; [...]
6376 //
6377 // Note that we already checked the context above, and that we do not have
6378 // enough information to make sure that Previous contains the declaration
6379 // we want to match. For example, given:
6380 //
6381 // class X {
6382 // void f();
6383 // void f(float);
6384 // };
6385 //
6386 // void X::f(int) { } // ill-formed
6387 //
6388 // In this case, Previous will point to the overload set
6389 // containing the two f's declared in X, but neither of them
6390 // matches.
6391
6393 }
6394
6395 if (Previous.isSingleResult() &&
6396 Previous.getFoundDecl()->isTemplateParameter()) {
6397 // Maybe we will complain about the shadowed template parameter.
6398 if (!D.isInvalidType())
6400 Previous.getFoundDecl());
6401
6402 // Just pretend that we didn't see the previous declaration.
6403 Previous.clear();
6404 }
6405
6406 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6407 // Forget that the previous declaration is the injected-class-name.
6408 Previous.clear();
6409
6410 // In C++, the previous declaration we find might be a tag type
6411 // (class or enum). In this case, the new declaration will hide the
6412 // tag type. Note that this applies to functions, function templates, and
6413 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6414 if (Previous.isSingleTagDecl() &&
6416 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6417 Previous.clear();
6418
6419 // Check that there are no default arguments other than in the parameters
6420 // of a function declaration (C++ only).
6421 if (getLangOpts().CPlusPlus)
6423
6424 NamedDecl *New;
6425
6426 bool AddToScope = true;
6428 if (TemplateParamLists.size()) {
6429 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6430 return nullptr;
6431 }
6432
6433 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6434 } else if (R->isFunctionType()) {
6435 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6436 TemplateParamLists,
6437 AddToScope);
6438 } else {
6439 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6440 AddToScope);
6441 }
6442
6443 if (!New)
6444 return nullptr;
6445
6446 // If this has an identifier and is not a function template specialization,
6447 // add it to the scope stack.
6448 if (New->getDeclName() && AddToScope)
6449 PushOnScopeChains(New, S);
6450
6453
6454 return New;
6455}
6456
6457/// Helper method to turn variable array types into constant array
6458/// types in certain situations which would otherwise be errors (for
6459/// GCC compatibility).
6461 ASTContext &Context,
6462 bool &SizeIsNegative,
6463 llvm::APSInt &Oversized) {
6464 // This method tries to turn a variable array into a constant
6465 // array even when the size isn't an ICE. This is necessary
6466 // for compatibility with code that depends on gcc's buggy
6467 // constant expression folding, like struct {char x[(int)(char*)2];}
6468 SizeIsNegative = false;
6469 Oversized = 0;
6470
6471 if (T->isDependentType())
6472 return QualType();
6473
6475 const Type *Ty = Qs.strip(T);
6476
6477 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6478 QualType Pointee = PTy->getPointeeType();
6479 QualType FixedType =
6480 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6481 Oversized);
6482 if (FixedType.isNull()) return FixedType;
6483 FixedType = Context.getPointerType(FixedType);
6484 return Qs.apply(Context, FixedType);
6485 }
6486 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6487 QualType Inner = PTy->getInnerType();
6488 QualType FixedType =
6489 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6490 Oversized);
6491 if (FixedType.isNull()) return FixedType;
6492 FixedType = Context.getParenType(FixedType);
6493 return Qs.apply(Context, FixedType);
6494 }
6495
6496 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6497 if (!VLATy)
6498 return QualType();
6499
6500 QualType ElemTy = VLATy->getElementType();
6501 if (ElemTy->isVariablyModifiedType()) {
6502 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6503 SizeIsNegative, Oversized);
6504 if (ElemTy.isNull())
6505 return QualType();
6506 }
6507
6509 if (!VLATy->getSizeExpr() ||
6510 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6511 return QualType();
6512
6513 llvm::APSInt Res = Result.Val.getInt();
6514
6515 // Check whether the array size is negative.
6516 if (Res.isSigned() && Res.isNegative()) {
6517 SizeIsNegative = true;
6518 return QualType();
6519 }
6520
6521 // Check whether the array is too large to be addressed.
6522 unsigned ActiveSizeBits =
6523 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6524 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6525 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6526 : Res.getActiveBits();
6527 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6528 Oversized = Res;
6529 return QualType();
6530 }
6531
6532 QualType FoldedArrayType = Context.getConstantArrayType(
6533 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6534 return Qs.apply(Context, FoldedArrayType);
6535}
6536
6537static void
6539 SrcTL = SrcTL.getUnqualifiedLoc();
6540 DstTL = DstTL.getUnqualifiedLoc();
6541 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6542 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6543 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6544 DstPTL.getPointeeLoc());
6545 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6546 return;
6547 }
6548 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6549 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6550 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6551 DstPTL.getInnerLoc());
6552 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6553 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6554 return;
6555 }
6556 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6557 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6558 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6559 TypeLoc DstElemTL = DstATL.getElementLoc();
6560 if (VariableArrayTypeLoc SrcElemATL =
6561 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6562 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6563 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6564 } else {
6565 DstElemTL.initializeFullCopy(SrcElemTL);
6566 }
6567 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6568 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6569 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6570}
6571
6572/// Helper method to turn variable array types into constant array
6573/// types in certain situations which would otherwise be errors (for
6574/// GCC compatibility).
6575static TypeSourceInfo*
6577 ASTContext &Context,
6578 bool &SizeIsNegative,
6579 llvm::APSInt &Oversized) {
6580 QualType FixedTy
6581 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6582 SizeIsNegative, Oversized);
6583 if (FixedTy.isNull())
6584 return nullptr;
6585 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6587 FixedTInfo->getTypeLoc());
6588 return FixedTInfo;
6589}
6590
6591/// Attempt to fold a variable-sized type to a constant-sized type, returning
6592/// true if we were successful.
6594 QualType &T, SourceLocation Loc,
6595 unsigned FailedFoldDiagID) {
6596 bool SizeIsNegative;
6597 llvm::APSInt Oversized;
6599 TInfo, Context, SizeIsNegative, Oversized);
6600 if (FixedTInfo) {
6601 Diag(Loc, diag::ext_vla_folded_to_constant);
6602 TInfo = FixedTInfo;
6603 T = FixedTInfo->getType();
6604 return true;
6605 }
6606
6607 if (SizeIsNegative)
6608 Diag(Loc, diag::err_typecheck_negative_array_size);
6609 else if (Oversized.getBoolValue())
6610 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6611 else if (FailedFoldDiagID)
6612 Diag(Loc, FailedFoldDiagID);
6613 return false;
6614}
6615
6616/// Register the given locally-scoped extern "C" declaration so
6617/// that it can be found later for redeclarations. We include any extern "C"
6618/// declaration that is not visible in the translation unit here, not just
6619/// function-scope declarations.
6620void
6622 if (!getLangOpts().CPlusPlus &&
6624 // Don't need to track declarations in the TU in C.
6625 return;
6626
6627 // Note that we have a locally-scoped external with this name.
6629}
6630
6632 // FIXME: We can have multiple results via __attribute__((overloadable)).
6634 return Result.empty() ? nullptr : *Result.begin();
6635}
6636
6637/// Diagnose function specifiers on a declaration of an identifier that
6638/// does not identify a function.
6640 // FIXME: We should probably indicate the identifier in question to avoid
6641 // confusion for constructs like "virtual int a(), b;"
6642 if (DS.isVirtualSpecified())
6644 diag::err_virtual_non_function);
6645
6646 if (DS.hasExplicitSpecifier())
6648 diag::err_explicit_non_function);
6649
6650 if (DS.isNoreturnSpecified())
6652 diag::err_noreturn_non_function);
6653}
6654
6655NamedDecl*
6658 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6659 if (D.getCXXScopeSpec().isSet()) {
6660 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6661 << D.getCXXScopeSpec().getRange();
6662 D.setInvalidType();
6663 // Pretend we didn't see the scope specifier.
6664 DC = CurContext;
6665 Previous.clear();
6666 }
6667
6669
6671 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6672 << getLangOpts().CPlusPlus17;
6674 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6675 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6676
6680 diag::err_deduction_guide_invalid_specifier)
6681 << "typedef";
6682 else
6683 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6684 << D.getName().getSourceRange();
6685 return nullptr;
6686 }
6687
6688 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6689 if (!NewTD) return nullptr;
6690
6691 // Handle attributes prior to checking for duplicates in MergeVarDecl
6692 ProcessDeclAttributes(S, NewTD, D);
6693
6695
6696 bool Redeclaration = D.isRedeclaration();
6697 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6698 D.setRedeclaration(Redeclaration);
6699 return ND;
6700}
6701
6702void
6704 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6705 // then it shall have block scope.
6706 // Note that variably modified types must be fixed before merging the decl so
6707 // that redeclarations will match.
6708 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6709 QualType T = TInfo->getType();
6710 if (T->isVariablyModifiedType()) {
6712
6713 if (S->getFnParent() == nullptr) {
6714 bool SizeIsNegative;
6715 llvm::APSInt Oversized;
6716 TypeSourceInfo *FixedTInfo =
6718 SizeIsNegative,
6719 Oversized);
6720 if (FixedTInfo) {
6721 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6722 NewTD->setTypeSourceInfo(FixedTInfo);
6723 } else {
6724 if (SizeIsNegative)
6725 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6726 else if (T->isVariableArrayType())
6727 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6728 else if (Oversized.getBoolValue())
6729 Diag(NewTD->getLocation(), diag::err_array_too_large)
6730 << toString(Oversized, 10);
6731 else
6732 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6733 NewTD->setInvalidDecl();
6734 }
6735 }
6736 }
6737}
6738
6739/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6740/// declares a typedef-name, either using the 'typedef' type specifier or via
6741/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6742NamedDecl*
6744 LookupResult &Previous, bool &Redeclaration) {
6745
6746 // Find the shadowed declaration before filtering for scope.
6747 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6748
6749 // Merge the decl with the existing one if appropriate. If the decl is
6750 // in an outer scope, it isn't the same thing.
6751 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6752 /*AllowInlineNamespace*/false);
6754 if (!Previous.empty()) {
6755 Redeclaration = true;
6756 MergeTypedefNameDecl(S, NewTD, Previous);
6757 } else {
6759 }
6760
6761 if (ShadowedDecl && !Redeclaration)
6762 CheckShadow(NewTD, ShadowedDecl, Previous);
6763
6764 // If this is the C FILE type, notify the AST context.
6765 if (IdentifierInfo *II = NewTD->getIdentifier())
6766 if (!NewTD->isInvalidDecl() &&
6768 switch (II->getInterestingIdentifierID()) {
6769 case tok::InterestingIdentifierKind::FILE:
6770 Context.setFILEDecl(NewTD);
6771 break;
6772 case tok::InterestingIdentifierKind::jmp_buf:
6773 Context.setjmp_bufDecl(NewTD);
6774 break;
6775 case tok::InterestingIdentifierKind::sigjmp_buf:
6777 break;
6778 case tok::InterestingIdentifierKind::ucontext_t:
6780 break;
6781 case tok::InterestingIdentifierKind::float_t:
6782 case tok::InterestingIdentifierKind::double_t:
6783 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6784 break;
6785 default:
6786 break;
6787 }
6788 }
6789
6790 return NewTD;
6791}
6792
6793/// Determines whether the given declaration is an out-of-scope
6794/// previous declaration.
6795///
6796/// This routine should be invoked when name lookup has found a
6797/// previous declaration (PrevDecl) that is not in the scope where a
6798/// new declaration by the same name is being introduced. If the new
6799/// declaration occurs in a local scope, previous declarations with
6800/// linkage may still be considered previous declarations (C99
6801/// 6.2.2p4-5, C++ [basic.link]p6).
6802///
6803/// \param PrevDecl the previous declaration found by name
6804/// lookup
6805///
6806/// \param DC the context in which the new declaration is being
6807/// declared.
6808///
6809/// \returns true if PrevDecl is an out-of-scope previous declaration
6810/// for a new delcaration with the same name.
6811static bool
6813 ASTContext &Context) {
6814 if (!PrevDecl)
6815 return false;
6816
6817 if (!PrevDecl->hasLinkage())
6818 return false;
6819
6820 if (Context.getLangOpts().CPlusPlus) {
6821 // C++ [basic.link]p6:
6822 // If there is a visible declaration of an entity with linkage
6823 // having the same name and type, ignoring entities declared
6824 // outside the innermost enclosing namespace scope, the block
6825 // scope declaration declares that same entity and receives the
6826 // linkage of the previous declaration.
6827 DeclContext *OuterContext = DC->getRedeclContext();
6828 if (!OuterContext->isFunctionOrMethod())
6829 // This rule only applies to block-scope declarations.
6830 return false;
6831
6832 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6833 if (PrevOuterContext->isRecord())
6834 // We found a member function: ignore it.
6835 return false;
6836
6837 // Find the innermost enclosing namespace for the new and
6838 // previous declarations.
6839 OuterContext = OuterContext->getEnclosingNamespaceContext();
6840 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6841
6842 // The previous declaration is in a different namespace, so it
6843 // isn't the same function.
6844 if (!OuterContext->Equals(PrevOuterContext))
6845 return false;
6846 }
6847
6848 return true;
6849}
6850
6852 CXXScopeSpec &SS = D.getCXXScopeSpec();
6853 if (!SS.isSet()) return;
6855}
6856
6858 QualType type = decl->getType();
6859 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6860 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6861 // Various kinds of declaration aren't allowed to be __autoreleasing.
6862 unsigned kind = -1U;
6863 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6864 if (var->hasAttr<BlocksAttr>())
6865 kind = 0; // __block
6866 else if (!var->hasLocalStorage())
6867 kind = 1; // global
6868 } else if (isa<ObjCIvarDecl>(decl)) {
6869 kind = 3; // ivar
6870 } else if (isa<FieldDecl>(decl)) {
6871 kind = 2; // field
6872 }
6873
6874 if (kind != -1U) {
6875 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6876 << kind;
6877 }
6878 } else if (lifetime == Qualifiers::OCL_None) {
6879 // Try to infer lifetime.
6880 if (!type->isObjCLifetimeType())
6881 return false;
6882
6883 lifetime = type->getObjCARCImplicitLifetime();
6884 type = Context.getLifetimeQualifiedType(type, lifetime);
6885 decl->setType(type);
6886 }
6887
6888 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6889 // Thread-local variables cannot have lifetime.
6890 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6891 var->getTLSKind()) {
6892 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6893 << var->getType();
6894 return true;
6895 }
6896 }
6897
6898 return false;
6899}
6900
6902 if (Decl->getType().hasAddressSpace())
6903 return;
6904 if (Decl->getType()->isDependentType())
6905 return;
6906 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6907 QualType Type = Var->getType();
6908 if (Type->isSamplerT() || Type->isVoidType())
6909 return;
6911 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6912 // __opencl_c_program_scope_global_variables feature, the address space
6913 // for a variable at program scope or a static or extern variable inside
6914 // a function are inferred to be __global.
6915 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6916 Var->hasGlobalStorage())
6917 ImplAS = LangAS::opencl_global;
6918 // If the original type from a decayed type is an array type and that array
6919 // type has no address space yet, deduce it now.
6920 if (auto DT = dyn_cast<DecayedType>(Type)) {
6921 auto OrigTy = DT->getOriginalType();
6922 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6923 // Add the address space to the original array type and then propagate
6924 // that to the element type through `getAsArrayType`.
6925 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6926 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6927 // Re-generate the decayed type.
6928 Type = Context.getDecayedType(OrigTy);
6929 }
6930 }
6932 // Apply any qualifiers (including address space) from the array type to
6933 // the element type. This implements C99 6.7.3p8: "If the specification of
6934 // an array type includes any type qualifiers, the element type is so
6935 // qualified, not the array type."
6936 if (Type->isArrayType())
6938 Decl->setType(Type);
6939 }
6940}
6941
6943 // Ensure that an auto decl is deduced otherwise the checks below might cache
6944 // the wrong linkage.
6945 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6946
6947 // 'weak' only applies to declarations with external linkage.
6948 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6949 if (!ND.isExternallyVisible()) {
6950 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6951 ND.dropAttr<WeakAttr>();
6952 }
6953 }
6954 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6955 if (ND.isExternallyVisible()) {
6956 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6957 ND.dropAttr<WeakRefAttr>();
6958 ND.dropAttr<AliasAttr>();
6959 }
6960 }
6961
6962 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6963 if (VD->hasInit()) {
6964 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6965 assert(VD->isThisDeclarationADefinition() &&
6966 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6967 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6968 VD->dropAttr<AliasAttr>();
6969 }
6970 }
6971 }
6972
6973 // 'selectany' only applies to externally visible variable declarations.
6974 // It does not apply to functions.
6975 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6976 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6977 S.Diag(Attr->getLocation(),
6978 diag::err_attribute_selectany_non_extern_data);
6979 ND.dropAttr<SelectAnyAttr>();
6980 }
6981 }
6982
6983 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6984 auto *VD = dyn_cast<VarDecl>(&ND);
6985 bool IsAnonymousNS = false;
6986 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6987 if (VD) {
6988 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6989 while (NS && !IsAnonymousNS) {
6990 IsAnonymousNS = NS->isAnonymousNamespace();
6991 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6992 }
6993 }
6994 // dll attributes require external linkage. Static locals may have external
6995 // linkage but still cannot be explicitly imported or exported.
6996 // In Microsoft mode, a variable defined in anonymous namespace must have
6997 // external linkage in order to be exported.
6998 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6999 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7000 (!AnonNSInMicrosoftMode &&
7001 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7002 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7003 << &ND << Attr;
7004 ND.setInvalidDecl();
7005 }
7006 }
7007
7008 // Check the attributes on the function type, if any.
7009 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7010 // Don't declare this variable in the second operand of the for-statement;
7011 // GCC miscompiles that by ending its lifetime before evaluating the
7012 // third operand. See gcc.gnu.org/PR86769.
7014 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7015 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7016 TL = ATL.getModifiedLoc()) {
7017 // The [[lifetimebound]] attribute can be applied to the implicit object
7018 // parameter of a non-static member function (other than a ctor or dtor)
7019 // by applying it to the function type.
7020 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7021 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7022 if (!MD || MD->isStatic()) {
7023 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7024 << !MD << A->getRange();
7025 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7026 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7027 << isa<CXXDestructorDecl>(MD) << A->getRange();
7028 }
7029 }
7030 }
7031 }
7032}
7033
7035 NamedDecl *NewDecl,
7036 bool IsSpecialization,
7037 bool IsDefinition) {
7038 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7039 return;
7040
7041 bool IsTemplate = false;
7042 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7043 OldDecl = OldTD->getTemplatedDecl();
7044 IsTemplate = true;
7045 if (!IsSpecialization)
7046 IsDefinition = false;
7047 }
7048 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7049 NewDecl = NewTD->getTemplatedDecl();
7050 IsTemplate = true;
7051 }
7052
7053 if (!OldDecl || !NewDecl)
7054 return;
7055
7056 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7057 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7058 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7059 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7060
7061 // dllimport and dllexport are inheritable attributes so we have to exclude
7062 // inherited attribute instances.
7063 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7064 (NewExportAttr && !NewExportAttr->isInherited());
7065
7066 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7067 // the only exception being explicit specializations.
7068 // Implicitly generated declarations are also excluded for now because there
7069 // is no other way to switch these to use dllimport or dllexport.
7070 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7071
7072 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7073 // Allow with a warning for free functions and global variables.
7074 bool JustWarn = false;
7075 if (!OldDecl->isCXXClassMember()) {
7076 auto *VD = dyn_cast<VarDecl>(OldDecl);
7077 if (VD && !VD->getDescribedVarTemplate())
7078 JustWarn = true;
7079 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7080 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7081 JustWarn = true;
7082 }
7083
7084 // We cannot change a declaration that's been used because IR has already
7085 // been emitted. Dllimported functions will still work though (modulo
7086 // address equality) as they can use the thunk.
7087 if (OldDecl->isUsed())
7088 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7089 JustWarn = false;
7090
7091 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7092 : diag::err_attribute_dll_redeclaration;
7093 S.Diag(NewDecl->getLocation(), DiagID)
7094 << NewDecl
7095 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7096 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7097 if (!JustWarn) {
7098 NewDecl->setInvalidDecl();
7099 return;
7100 }
7101 }
7102
7103 // A redeclaration is not allowed to drop a dllimport attribute, the only
7104 // exceptions being inline function definitions (except for function
7105 // templates), local extern declarations, qualified friend declarations or
7106 // special MSVC extension: in the last case, the declaration is treated as if
7107 // it were marked dllexport.
7108 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7109 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7110 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7111 // Ignore static data because out-of-line definitions are diagnosed
7112 // separately.
7113 IsStaticDataMember = VD->isStaticDataMember();
7114 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7116 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7117 IsInline = FD->isInlined();
7118 IsQualifiedFriend = FD->getQualifier() &&
7119 FD->getFriendObjectKind() == Decl::FOK_Declared;
7120 }
7121
7122 if (OldImportAttr && !HasNewAttr &&
7123 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7124 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7125 if (IsMicrosoftABI && IsDefinition) {
7126 if (IsSpecialization) {
7127 S.Diag(
7128 NewDecl->getLocation(),
7129 diag::err_attribute_dllimport_function_specialization_definition);
7130 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7131 NewDecl->dropAttr<DLLImportAttr>();
7132 } else {
7133 S.Diag(NewDecl->getLocation(),
7134 diag::warn_redeclaration_without_import_attribute)
7135 << NewDecl;
7136 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7137 NewDecl->dropAttr<DLLImportAttr>();
7138 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7139 S.Context, NewImportAttr->getRange()));
7140 }
7141 } else if (IsMicrosoftABI && IsSpecialization) {
7142 assert(!IsDefinition);
7143 // MSVC allows this. Keep the inherited attribute.
7144 } else {
7145 S.Diag(NewDecl->getLocation(),
7146 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7147 << NewDecl << OldImportAttr;
7148 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7149 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7150 OldDecl->dropAttr<DLLImportAttr>();
7151 NewDecl->dropAttr<DLLImportAttr>();
7152 }
7153 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7154 // In MinGW, seeing a function declared inline drops the dllimport
7155 // attribute.
7156 OldDecl->dropAttr<DLLImportAttr>();
7157 NewDecl->dropAttr<DLLImportAttr>();
7158 S.Diag(NewDecl->getLocation(),
7159 diag::warn_dllimport_dropped_from_inline_function)
7160 << NewDecl << OldImportAttr;
7161 }
7162
7163 // A specialization of a class template member function is processed here
7164 // since it's a redeclaration. If the parent class is dllexport, the
7165 // specialization inherits that attribute. This doesn't happen automatically
7166 // since the parent class isn't instantiated until later.
7167 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7168 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7169 !NewImportAttr && !NewExportAttr) {
7170 if (const DLLExportAttr *ParentExportAttr =
7171 MD->getParent()->getAttr<DLLExportAttr>()) {
7172 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7173 NewAttr->setInherited(true);
7174 NewDecl->addAttr(NewAttr);
7175 }
7176 }
7177 }
7178}
7179
7180/// Given that we are within the definition of the given function,
7181/// will that definition behave like C99's 'inline', where the
7182/// definition is discarded except for optimization purposes?
7184 // Try to avoid calling GetGVALinkageForFunction.
7185
7186 // All cases of this require the 'inline' keyword.
7187 if (!FD->isInlined()) return false;
7188
7189 // This is only possible in C++ with the gnu_inline attribute.
7190 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7191 return false;
7192
7193 // Okay, go ahead and call the relatively-more-expensive function.
7195}
7196
7197/// Determine whether a variable is extern "C" prior to attaching
7198/// an initializer. We can't just call isExternC() here, because that
7199/// will also compute and cache whether the declaration is externally
7200/// visible, which might change when we attach the initializer.
7201///
7202/// This can only be used if the declaration is known to not be a
7203/// redeclaration of an internal linkage declaration.
7204///
7205/// For instance:
7206///
7207/// auto x = []{};
7208///
7209/// Attaching the initializer here makes this declaration not externally
7210/// visible, because its type has internal linkage.
7211///
7212/// FIXME: This is a hack.
7213template<typename T>
7214static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7215 if (S.getLangOpts().CPlusPlus) {
7216 // In C++, the overloadable attribute negates the effects of extern "C".
7217 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7218 return false;
7219
7220 // So do CUDA's host/device attributes.
7221 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7222 D->template hasAttr<CUDAHostAttr>()))
7223 return false;
7224 }
7225 return D->isExternC();
7226}
7227
7228static bool shouldConsiderLinkage(const VarDecl *VD) {
7229 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7230 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7231 isa<OMPDeclareMapperDecl>(DC))
7232 return VD->hasExternalStorage();
7233 if (DC->isFileContext())
7234 return true;
7235 if (DC->isRecord())
7236 return false;
7237 if (DC->getDeclKind() == Decl::HLSLBuffer)
7238 return false;
7239
7240 if (isa<RequiresExprBodyDecl>(DC))
7241 return false;
7242 llvm_unreachable("Unexpected context");
7243}
7244
7245static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7246 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7247 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7248 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7249 return true;
7250 if (DC->isRecord())
7251 return false;
7252 llvm_unreachable("Unexpected context");
7253}
7254
7255static bool hasParsedAttr(Scope *S, const Declarator &PD,
7256 ParsedAttr::Kind Kind) {
7257 // Check decl attributes on the DeclSpec.
7258 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7259 return true;
7260
7261 // Walk the declarator structure, checking decl attributes that were in a type
7262 // position to the decl itself.
7263 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7264 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7265 return true;
7266 }
7267
7268 // Finally, check attributes on the decl itself.
7269 return PD.getAttributes().hasAttribute(Kind) ||
7271}
7272
7273/// Adjust the \c DeclContext for a function or variable that might be a
7274/// function-local external declaration.
7276 if (!DC->isFunctionOrMethod())
7277 return false;
7278
7279 // If this is a local extern function or variable declared within a function
7280 // template, don't add it into the enclosing namespace scope until it is
7281 // instantiated; it might have a dependent type right now.
7282 if (DC->isDependentContext())
7283 return true;
7284
7285 // C++11 [basic.link]p7:
7286 // When a block scope declaration of an entity with linkage is not found to
7287 // refer to some other declaration, then that entity is a member of the
7288 // innermost enclosing namespace.
7289 //
7290 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7291 // semantically-enclosing namespace, not a lexically-enclosing one.
7292 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7293 DC = DC->getParent();
7294 return true;
7295}
7296
7297/// Returns true if given declaration has external C language linkage.
7298static bool isDeclExternC(const Decl *D) {
7299 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7300 return FD->isExternC();
7301 if (const auto *VD = dyn_cast<VarDecl>(D))
7302 return VD->isExternC();
7303
7304 llvm_unreachable("Unknown type of decl!");
7305}
7306
7307/// Returns true if there hasn't been any invalid type diagnosed.
7308static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7309 DeclContext *DC = NewVD->getDeclContext();
7310 QualType R = NewVD->getType();
7311
7312 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7313 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7314 // argument.
7315 if (R->isImageType() || R->isPipeType()) {
7316 Se.Diag(NewVD->getLocation(),
7317 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7318 << R;
7319 NewVD->setInvalidDecl();
7320 return false;
7321 }
7322
7323 // OpenCL v1.2 s6.9.r:
7324 // The event type cannot be used to declare a program scope variable.
7325 // OpenCL v2.0 s6.9.q:
7326 // The clk_event_t and reserve_id_t types cannot be declared in program
7327 // scope.
7328 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7329 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7330 Se.Diag(NewVD->getLocation(),
7331 diag::err_invalid_type_for_program_scope_var)
7332 << R;
7333 NewVD->setInvalidDecl();
7334 return false;
7335 }
7336 }
7337
7338 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7339 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7340 Se.getLangOpts())) {
7341 QualType NR = R.getCanonicalType();
7342 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7343 NR->isReferenceType()) {
7346 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7347 << NR->isReferenceType();
7348 NewVD->setInvalidDecl();
7349 return false;
7350 }
7351 NR = NR->getPointeeType();
7352 }
7353 }
7354
7355 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7356 Se.getLangOpts())) {
7357 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7358 // half array type (unless the cl_khr_fp16 extension is enabled).
7359 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7360 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7361 NewVD->setInvalidDecl();
7362 return false;
7363 }
7364 }
7365
7366 // OpenCL v1.2 s6.9.r:
7367 // The event type cannot be used with the __local, __constant and __global
7368 // address space qualifiers.
7369 if (R->isEventT()) {
7371 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7372 NewVD->setInvalidDecl();
7373 return false;
7374 }
7375 }
7376
7377 if (R->isSamplerT()) {
7378 // OpenCL v1.2 s6.9.b p4:
7379 // The sampler type cannot be used with the __local and __global address
7380 // space qualifiers.
7383 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7384 NewVD->setInvalidDecl();
7385 }
7386
7387 // OpenCL v1.2 s6.12.14.1:
7388 // A global sampler must be declared with either the constant address
7389 // space qualifier or with the const qualifier.
7390 if (DC->isTranslationUnit() &&
7392 R.isConstQualified())) {
7393 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7394 NewVD->setInvalidDecl();
7395 }
7396 if (NewVD->isInvalidDecl())
7397 return false;
7398 }
7399
7400 return true;
7401}
7402
7403template <typename AttrTy>
7404static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7405 const TypedefNameDecl *TND = TT->getDecl();
7406 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7407 AttrTy *Clone = Attribute->clone(S.Context);
7408 Clone->setInherited(true);
7409 D->addAttr(Clone);
7410 }
7411}
7412
7413// This function emits warning and a corresponding note based on the
7414// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7415// declarations of an annotated type must be const qualified.
7417 QualType VarType = VD->getType().getCanonicalType();
7418
7419 // Ignore local declarations (for now) and those with const qualification.
7420 // TODO: Local variables should not be allowed if their type declaration has
7421 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7422 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7423 return;
7424
7425 if (VarType->isArrayType()) {
7426 // Retrieve element type for array declarations.
7427 VarType = S.getASTContext().getBaseElementType(VarType);
7428 }
7429
7430 const RecordDecl *RD = VarType->getAsRecordDecl();
7431
7432 // Check if the record declaration is present and if it has any attributes.
7433 if (RD == nullptr)
7434 return;
7435
7436 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7437 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7438 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7439 return;
7440 }
7441}
7442
7444 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7445 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7446 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7447 QualType R = TInfo->getType();
7449
7450 IdentifierInfo *II = Name.getAsIdentifierInfo();
7451
7452 if (D.isDecompositionDeclarator()) {
7453 // Take the name of the first declarator as our name for diagnostic
7454 // purposes.
7455 auto &Decomp = D.getDecompositionDeclarator();
7456 if (!Decomp.bindings().empty()) {
7457 II = Decomp.bindings()[0].Name;
7458 Name = II;
7459 }
7460 } else if (!II) {
7461 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7462 return nullptr;
7463 }
7464
7465
7468
7469 // dllimport globals without explicit storage class are treated as extern. We
7470 // have to change the storage class this early to get the right DeclContext.
7471 if (SC == SC_None && !DC->isRecord() &&
7472 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7473 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7474 SC = SC_Extern;
7475
7476 DeclContext *OriginalDC = DC;
7477 bool IsLocalExternDecl = SC == SC_Extern &&
7479
7480 if (SCSpec == DeclSpec::SCS_mutable) {
7481 // mutable can only appear on non-static class members, so it's always
7482 // an error here
7483 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7484 D.setInvalidType();
7485 SC = SC_None;
7486 }
7487
7488 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7489 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7491 // In C++11, the 'register' storage class specifier is deprecated.
7492 // Suppress the warning in system macros, it's used in macros in some
7493 // popular C system headers, such as in glibc's htonl() macro.
7495 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7496 : diag::warn_deprecated_register)
7498 }
7499
7501
7502 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7503 // C99 6.9p2: The storage-class specifiers auto and register shall not
7504 // appear in the declaration specifiers in an external declaration.
7505 // Global Register+Asm is a GNU extension we support.
7506 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7507 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7508 D.setInvalidType();
7509 }
7510 }
7511
7512 // If this variable has a VLA type and an initializer, try to
7513 // fold to a constant-sized type. This is otherwise invalid.
7514 if (D.hasInitializer() && R->isVariableArrayType())
7516 /*DiagID=*/0);
7517
7518 bool IsMemberSpecialization = false;
7519 bool IsVariableTemplateSpecialization = false;
7520 bool IsPartialSpecialization = false;
7521 bool IsVariableTemplate = false;
7522 VarDecl *NewVD = nullptr;
7523 VarTemplateDecl *NewTemplate = nullptr;
7524 TemplateParameterList *TemplateParams = nullptr;
7525 if (!getLangOpts().CPlusPlus) {
7527 II, R, TInfo, SC);
7528
7529 if (R->getContainedDeducedType())
7530 ParsingInitForAutoVars.insert(NewVD);
7531
7532 if (D.isInvalidType())
7533 NewVD->setInvalidDecl();
7534
7536 NewVD->hasLocalStorage())
7537 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7539 } else {
7540 bool Invalid = false;
7541
7542 if (DC->isRecord() && !CurContext->isRecord()) {
7543 // This is an out-of-line definition of a static data member.
7544 switch (SC) {
7545 case SC_None:
7546 break;
7547 case SC_Static:
7549 diag::err_static_out_of_line)
7551 break;
7552 case SC_Auto:
7553 case SC_Register:
7554 case SC_Extern:
7555 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7556 // to names of variables declared in a block or to function parameters.
7557 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7558 // of class members
7559
7561 diag::err_storage_class_for_static_member)
7563 break;
7564 case SC_PrivateExtern:
7565 llvm_unreachable("C storage class in c++!");
7566 }
7567 }
7568
7569 if (SC == SC_Static && CurContext->isRecord()) {
7570 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7571 // Walk up the enclosing DeclContexts to check for any that are
7572 // incompatible with static data members.
7573 const DeclContext *FunctionOrMethod = nullptr;
7574 const CXXRecordDecl *AnonStruct = nullptr;
7575 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7576 if (Ctxt->isFunctionOrMethod()) {
7577 FunctionOrMethod = Ctxt;
7578 break;
7579 }
7580 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7581 if (ParentDecl && !ParentDecl->getDeclName()) {
7582 AnonStruct = ParentDecl;
7583 break;
7584 }
7585 }
7586 if (FunctionOrMethod) {
7587 // C++ [class.static.data]p5: A local class shall not have static data
7588 // members.
7590 diag::err_static_data_member_not_allowed_in_local_class)
7591 << Name << RD->getDeclName() << RD->getTagKind();
7592 } else if (AnonStruct) {
7593 // C++ [class.static.data]p4: Unnamed classes and classes contained
7594 // directly or indirectly within unnamed classes shall not contain
7595 // static data members.
7597 diag::err_static_data_member_not_allowed_in_anon_struct)
7598 << Name << AnonStruct->getTagKind();
7599 Invalid = true;
7600 } else if (RD->isUnion()) {
7601 // C++98 [class.union]p1: If a union contains a static data member,
7602 // the program is ill-formed. C++11 drops this restriction.
7605 ? diag::warn_cxx98_compat_static_data_member_in_union
7606 : diag::ext_static_data_member_in_union) << Name;
7607 }
7608 }
7609 }
7610
7611 // Match up the template parameter lists with the scope specifier, then
7612 // determine whether we have a template or a template specialization.
7613 bool InvalidScope = false;
7616 D.getCXXScopeSpec(),
7618 ? D.getName().TemplateId
7619 : nullptr,
7620 TemplateParamLists,
7621 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7622 Invalid |= InvalidScope;
7623
7624 if (TemplateParams) {
7625 if (!TemplateParams->size() &&
7627 // There is an extraneous 'template<>' for this variable. Complain
7628 // about it, but allow the declaration of the variable.
7629 Diag(TemplateParams->getTemplateLoc(),
7630 diag::err_template_variable_noparams)
7631 << II
7632 << SourceRange(TemplateParams->getTemplateLoc(),
7633 TemplateParams->getRAngleLoc());
7634 TemplateParams = nullptr;
7635 } else {
7636 // Check that we can declare a template here.
7637 if (CheckTemplateDeclScope(S, TemplateParams))
7638 return nullptr;
7639
7641 // This is an explicit specialization or a partial specialization.
7642 IsVariableTemplateSpecialization = true;
7643 IsPartialSpecialization = TemplateParams->size() > 0;
7644 } else { // if (TemplateParams->size() > 0)
7645 // This is a template declaration.
7646 IsVariableTemplate = true;
7647
7648 // Only C++1y supports variable templates (N3651).
7651 ? diag::warn_cxx11_compat_variable_template
7652 : diag::ext_variable_template);
7653 }
7654 }
7655 } else {
7656 // Check that we can declare a member specialization here.
7657 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7658 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7659 return nullptr;
7660 assert((Invalid ||
7662 "should have a 'template<>' for this decl");
7663 }
7664
7665 if (IsVariableTemplateSpecialization) {
7666 SourceLocation TemplateKWLoc =
7667 TemplateParamLists.size() > 0
7668 ? TemplateParamLists[0]->getTemplateLoc()
7669 : SourceLocation();
7671 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7673 if (Res.isInvalid())
7674 return nullptr;
7675 NewVD = cast<VarDecl>(Res.get());
7676 AddToScope = false;
7677 } else if (D.isDecompositionDeclarator()) {
7679 D.getIdentifierLoc(), R, TInfo, SC,
7680 Bindings);
7681 } else
7682 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7683 D.getIdentifierLoc(), II, R, TInfo, SC);
7684
7685 // If this is supposed to be a variable template, create it as such.
7686 if (IsVariableTemplate) {
7687 NewTemplate =
7689 TemplateParams, NewVD);
7690 NewVD->setDescribedVarTemplate(NewTemplate);
7691 }
7692
7693 // If this decl has an auto type in need of deduction, make a note of the
7694 // Decl so we can diagnose uses of it in its own initializer.
7695 if (R->getContainedDeducedType())
7696 ParsingInitForAutoVars.insert(NewVD);
7697
7698 if (D.isInvalidType() || Invalid) {
7699 NewVD->setInvalidDecl();
7700 if (NewTemplate)
7701 NewTemplate->setInvalidDecl();
7702 }
7703
7704 SetNestedNameSpecifier(*this, NewVD, D);
7705
7706 // If we have any template parameter lists that don't directly belong to
7707 // the variable (matching the scope specifier), store them.
7708 // An explicit variable template specialization does not own any template
7709 // parameter lists.
7710 bool IsExplicitSpecialization =
7711 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7712 unsigned VDTemplateParamLists =
7713 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7714 if (TemplateParamLists.size() > VDTemplateParamLists)
7716 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7717 }
7718
7719 if (D.getDeclSpec().isInlineSpecified()) {
7720 if (!getLangOpts().CPlusPlus) {
7721 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7722 << 0;
7723 } else if (CurContext->isFunctionOrMethod()) {
7724 // 'inline' is not allowed on block scope variable declaration.
7726 diag::err_inline_declaration_block_scope) << Name
7728 } else {
7730 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7731 : diag::ext_inline_variable);
7732 NewVD->setInlineSpecified();
7733 }
7734 }
7735
7736 // Set the lexical context. If the declarator has a C++ scope specifier, the
7737 // lexical context will be different from the semantic context.
7739 if (NewTemplate)
7740 NewTemplate->setLexicalDeclContext(CurContext);
7741
7742 if (IsLocalExternDecl) {
7744 for (auto *B : Bindings)
7745 B->setLocalExternDecl();
7746 else
7747 NewVD->setLocalExternDecl();
7748 }
7749
7750 bool EmitTLSUnsupportedError = false;
7752 // C++11 [dcl.stc]p4:
7753 // When thread_local is applied to a variable of block scope the
7754 // storage-class-specifier static is implied if it does not appear
7755 // explicitly.
7756 // Core issue: 'static' is not implied if the variable is declared
7757 // 'extern'.
7758 if (NewVD->hasLocalStorage() &&
7759 (SCSpec != DeclSpec::SCS_unspecified ||
7761 !DC->isFunctionOrMethod()))
7763 diag::err_thread_non_global)
7765 else if (!Context.getTargetInfo().isTLSSupported()) {
7766 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7767 getLangOpts().SYCLIsDevice) {
7768 // Postpone error emission until we've collected attributes required to
7769 // figure out whether it's a host or device variable and whether the
7770 // error should be ignored.
7771 EmitTLSUnsupportedError = true;
7772 // We still need to mark the variable as TLS so it shows up in AST with
7773 // proper storage class for other tools to use even if we're not going
7774 // to emit any code for it.
7775 NewVD->setTSCSpec(TSCS);
7776 } else
7778 diag::err_thread_unsupported);
7779 } else
7780 NewVD->setTSCSpec(TSCS);
7781 }
7782
7783 switch (D.getDeclSpec().getConstexprSpecifier()) {
7785 break;
7786
7789 diag::err_constexpr_wrong_decl_kind)
7790 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7791 [[fallthrough]];
7792
7794 NewVD->setConstexpr(true);
7795 // C++1z [dcl.spec.constexpr]p1:
7796 // A static data member declared with the constexpr specifier is
7797 // implicitly an inline variable.
7798 if (NewVD->isStaticDataMember() &&
7801 NewVD->setImplicitlyInline();
7802 break;
7803
7805 if (!NewVD->hasGlobalStorage())
7807 diag::err_constinit_local_variable);
7808 else
7809 NewVD->addAttr(
7810 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7811 ConstInitAttr::Keyword_constinit));
7812 break;
7813 }
7814
7815 // C99 6.7.4p3
7816 // An inline definition of a function with external linkage shall
7817 // not contain a definition of a modifiable object with static or
7818 // thread storage duration...
7819 // We only apply this when the function is required to be defined
7820 // elsewhere, i.e. when the function is not 'extern inline'. Note
7821 // that a local variable with thread storage duration still has to
7822 // be marked 'static'. Also note that it's possible to get these
7823 // semantics in C++ using __attribute__((gnu_inline)).
7824 if (SC == SC_Static && S->getFnParent() != nullptr &&
7825 !NewVD->getType().isConstQualified()) {
7827 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7829 diag::warn_static_local_in_extern_inline);
7831 }
7832 }
7833
7835 if (IsVariableTemplateSpecialization)
7836 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7837 << (IsPartialSpecialization ? 1 : 0)
7840 else if (IsMemberSpecialization)
7841 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7842 << 2
7844 else if (NewVD->hasLocalStorage())
7845 Diag(NewVD->getLocation(), diag::err_module_private_local)
7846 << 0 << NewVD
7850 else {
7851 NewVD->setModulePrivate();
7852 if (NewTemplate)
7853 NewTemplate->setModulePrivate();
7854 for (auto *B : Bindings)
7855 B->setModulePrivate();
7856 }
7857 }
7858
7859 if (getLangOpts().OpenCL) {
7861
7863 if (TSC != TSCS_unspecified) {
7865 diag::err_opencl_unknown_type_specifier)
7867 << DeclSpec::getSpecifierName(TSC) << 1;
7868 NewVD->setInvalidDecl();
7869 }
7870 }
7871
7872 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7873 // address space if the table has local storage (semantic checks elsewhere
7874 // will produce an error anyway).
7875 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7876 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7877 !NewVD->hasLocalStorage()) {
7880 NewVD->setType(Type);
7881 }
7882 }
7883
7884 // Handle attributes prior to checking for duplicates in MergeVarDecl
7885 ProcessDeclAttributes(S, NewVD, D);
7886
7887 // FIXME: This is probably the wrong location to be doing this and we should
7888 // probably be doing this for more attributes (especially for function
7889 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7890 // the code to copy attributes would be generated by TableGen.
7891 if (R->isFunctionPointerType())
7892 if (const auto *TT = R->getAs<TypedefType>())
7894
7895 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7896 getLangOpts().SYCLIsDevice) {
7897 if (EmitTLSUnsupportedError &&
7899 (getLangOpts().OpenMPIsTargetDevice &&
7900 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7902 diag::err_thread_unsupported);
7903
7904 if (EmitTLSUnsupportedError &&
7905 (LangOpts.SYCLIsDevice ||
7906 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7907 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7908 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7909 // storage [duration]."
7910 if (SC == SC_None && S->getFnParent() != nullptr &&
7911 (NewVD->hasAttr<CUDASharedAttr>() ||
7912 NewVD->hasAttr<CUDAConstantAttr>())) {
7913 NewVD->setStorageClass(SC_Static);
7914 }
7915 }
7916
7917 // Ensure that dllimport globals without explicit storage class are treated as
7918 // extern. The storage class is set above using parsed attributes. Now we can
7919 // check the VarDecl itself.
7920 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7921 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7922 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7923
7924 // In auto-retain/release, infer strong retension for variables of
7925 // retainable type.
7926 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7927 NewVD->setInvalidDecl();
7928
7929 // Handle GNU asm-label extension (encoded as an attribute).
7930 if (Expr *E = (Expr*)D.getAsmLabel()) {
7931 // The parser guarantees this is a string.
7933 StringRef Label = SE->getString();
7934 if (S->getFnParent() != nullptr) {
7935 switch (SC) {
7936 case SC_None:
7937 case SC_Auto:
7938 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7939 break;
7940 case SC_Register:
7941 // Local Named register
7944 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7945 break;
7946 case SC_Static:
7947 case SC_Extern:
7948 case SC_PrivateExtern:
7949 break;
7950 }
7951 } else if (SC == SC_Register) {
7952 // Global Named register
7953 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7954 const auto &TI = Context.getTargetInfo();
7955 bool HasSizeMismatch;
7956
7957 if (!TI.isValidGCCRegisterName(Label))
7958 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7959 else if (!TI.validateGlobalRegisterVariable(Label,
7961 HasSizeMismatch))
7962 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7963 else if (HasSizeMismatch)
7964 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7965 }
7966
7967 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7968 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7969 NewVD->setInvalidDecl(true);
7970 }
7971 }
7972
7973 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7974 /*IsLiteralLabel=*/true,
7975 SE->getStrTokenLoc(0)));
7976 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7977 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7979 if (I != ExtnameUndeclaredIdentifiers.end()) {
7980 if (isDeclExternC(NewVD)) {
7981 NewVD->addAttr(I->second);
7983 } else
7984 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7985 << /*Variable*/1 << NewVD;
7986 }
7987 }
7988
7989 // Find the shadowed declaration before filtering for scope.
7990 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7992 : nullptr;
7993
7994 // Don't consider existing declarations that are in a different
7995 // scope and are out-of-semantic-context declarations (if the new
7996 // declaration has linkage).
7999 IsMemberSpecialization ||
8000 IsVariableTemplateSpecialization);
8001
8002 // Check whether the previous declaration is in the same block scope. This
8003 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8004 if (getLangOpts().CPlusPlus &&
8005 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8007 Previous.isSingleResult() && !Previous.isShadowed() &&
8008 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8009
8010 if (!getLangOpts().CPlusPlus) {
8012 } else {
8013 // If this is an explicit specialization of a static data member, check it.
8014 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8016 NewVD->setInvalidDecl();
8017
8018 // Merge the decl with the existing one if appropriate.
8019 if (!Previous.empty()) {
8020 if (Previous.isSingleResult() &&
8021 isa<FieldDecl>(Previous.getFoundDecl()) &&
8022 D.getCXXScopeSpec().isSet()) {
8023 // The user tried to define a non-static data member
8024 // out-of-line (C++ [dcl.meaning]p1).
8025 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8026 << D.getCXXScopeSpec().getRange();
8027 Previous.clear();
8028 NewVD->setInvalidDecl();
8029 }
8030 } else if (D.getCXXScopeSpec().isSet()) {
8031 // No previous declaration in the qualifying scope.
8032 Diag(D.getIdentifierLoc(), diag::err_no_member)
8033 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8034 << D.getCXXScopeSpec().getRange();
8035 NewVD->setInvalidDecl();
8036 }
8037
8038 if (!IsVariableTemplateSpecialization)
8040
8041 // CheckVariableDeclaration will set NewVD as invalid if something is in
8042 // error like WebAssembly tables being declared as arrays with a non-zero
8043 // size, but then parsing continues and emits further errors on that line.
8044 // To avoid that we check here if it happened and return nullptr.
8045 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8046 return nullptr;
8047
8048 if (NewTemplate) {
8049 VarTemplateDecl *PrevVarTemplate =
8050 NewVD->getPreviousDecl()
8052 : nullptr;
8053
8054 // Check the template parameter list of this declaration, possibly
8055 // merging in the template parameter list from the previous variable
8056 // template declaration.
8058 TemplateParams,
8059 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8060 : nullptr,
8061 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8062 DC->isDependentContext())
8064 : TPC_VarTemplate))
8065 NewVD->setInvalidDecl();
8066
8067 // If we are providing an explicit specialization of a static variable
8068 // template, make a note of that.
8069 if (PrevVarTemplate &&
8070 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8071 PrevVarTemplate->setMemberSpecialization();
8072 }
8073 }
8074
8075 // Diagnose shadowed variables iff this isn't a redeclaration.
8076 if (ShadowedDecl && !D.isRedeclaration())
8077 CheckShadow(NewVD, ShadowedDecl, Previous);
8078
8079 ProcessPragmaWeak(S, NewVD);
8080
8081 // If this is the first declaration of an extern C variable, update
8082 // the map of such variables.
8083 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8084 isIncompleteDeclExternC(*this, NewVD))
8086
8087 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8089 Decl *ManglingContextDecl;
8090 std::tie(MCtx, ManglingContextDecl) =
8092 if (MCtx) {
8094 NewVD, MCtx->getManglingNumber(
8095 NewVD, getMSManglingNumber(getLangOpts(), S)));
8097 }
8098 }
8099
8100 // Special handling of variable named 'main'.
8101 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8103 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8104
8105 // C++ [basic.start.main]p3
8106 // A program that declares a variable main at global scope is ill-formed.
8107 if (getLangOpts().CPlusPlus)
8108 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8109
8110 // In C, and external-linkage variable named main results in undefined
8111 // behavior.
8112 else if (NewVD->hasExternalFormalLinkage())
8113 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8114 }
8115
8116 if (D.isRedeclaration() && !Previous.empty()) {
8117 NamedDecl *Prev = Previous.getRepresentativeDecl();
8118 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8120 }
8121
8122 if (NewTemplate) {
8123 if (NewVD->isInvalidDecl())
8124 NewTemplate->setInvalidDecl();
8125 ActOnDocumentableDecl(NewTemplate);
8126 return NewTemplate;
8127 }
8128
8129 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8131
8133
8134 return NewVD;
8135}
8136
8137/// Enum describing the %select options in diag::warn_decl_shadow.
8147
8148/// Determine what kind of declaration we're shadowing.
8150 const DeclContext *OldDC) {
8151 if (isa<TypeAliasDecl>(ShadowedDecl))
8152 return SDK_Using;
8153 else if (isa<TypedefDecl>(ShadowedDecl))
8154 return SDK_Typedef;
8155 else if (isa<BindingDecl>(ShadowedDecl))
8156 return SDK_StructuredBinding;
8157 else if (isa<RecordDecl>(OldDC))
8158 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8159
8160 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8161}
8162
8163/// Return the location of the capture if the given lambda captures the given
8164/// variable \p VD, or an invalid source location otherwise.
8166 const VarDecl *VD) {
8167 for (const Capture &Capture : LSI->Captures) {
8169 return Capture.getLocation();
8170 }
8171 return SourceLocation();
8172}
8173
8175 const LookupResult &R) {
8176 // Only diagnose if we're shadowing an unambiguous field or variable.
8178 return false;
8179
8180 // Return false if warning is ignored.
8181 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8182}
8183
8184/// Return the declaration shadowed by the given variable \p D, or null
8185/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8187 const LookupResult &R) {
8189 return nullptr;
8190
8191 // Don't diagnose declarations at file scope.
8192 if (D->hasGlobalStorage() && !D->isStaticLocal())
8193 return nullptr;
8194
8195 NamedDecl *ShadowedDecl = R.getFoundDecl();
8196 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8197 : nullptr;
8198}
8199
8200/// Return the declaration shadowed by the given typedef \p D, or null
8201/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8203 const LookupResult &R) {
8204 // Don't warn if typedef declaration is part of a class
8205 if (D->getDeclContext()->isRecord())
8206 return nullptr;
8207
8209 return nullptr;
8210
8211 NamedDecl *ShadowedDecl = R.getFoundDecl();
8212 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8213}
8214
8215/// Return the declaration shadowed by the given variable \p D, or null
8216/// if it doesn't shadow any declaration or shadowing warnings are disabled.
8218 const LookupResult &R) {
8220 return nullptr;
8221
8222 NamedDecl *ShadowedDecl = R.getFoundDecl();
8223 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8224 : nullptr;
8225}
8226
8227/// Diagnose variable or built-in function shadowing. Implements
8228/// -Wshadow.
8229///
8230/// This method is called whenever a VarDecl is added to a "useful"
8231/// scope.
8232///
8233/// \param ShadowedDecl the declaration that is shadowed by the given variable
8234/// \param R the lookup of the name
8235///
8237 const LookupResult &R) {
8238 DeclContext *NewDC = D->getDeclContext();
8239
8240 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8241 // Fields are not shadowed by variables in C++ static methods.
8242 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8243 if (MD->isStatic())
8244 return;
8245
8246 // Fields shadowed by constructor parameters are a special case. Usually
8247 // the constructor initializes the field with the parameter.
8248 if (isa<CXXConstructorDecl>(NewDC))
8249 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8250 // Remember that this was shadowed so we can either warn about its
8251 // modification or its existence depending on warning settings.
8252 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8253 return;
8254 }
8255 }
8256
8257 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8258 if (shadowedVar->isExternC()) {
8259 // For shadowing external vars, make sure that we point to the global
8260 // declaration, not a locally scoped extern declaration.
8261 for (auto *I : shadowedVar->redecls())
8262 if (I->isFileVarDecl()) {
8263 ShadowedDecl = I;
8264 break;
8265 }
8266 }
8267
8268 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8269
8270 unsigned WarningDiag = diag::warn_decl_shadow;
8271 SourceLocation CaptureLoc;
8272 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8273 isa<CXXMethodDecl>(NewDC)) {
8274 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8275 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8276 if (RD->getLambdaCaptureDefault() == LCD_None) {
8277 // Try to avoid warnings for lambdas with an explicit capture list.
8278 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8279 // Warn only when the lambda captures the shadowed decl explicitly.
8280 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8281 if (CaptureLoc.isInvalid())
8282 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8283 } else {
8284 // Remember that this was shadowed so we can avoid the warning if the
8285 // shadowed decl isn't captured and the warning settings allow it.
8287 ->ShadowingDecls.push_back(
8288 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8289 return;
8290 }
8291 }
8292
8293 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8294 // A variable can't shadow a local variable in an enclosing scope, if
8295 // they are separated by a non-capturing declaration context.
8296 for (DeclContext *ParentDC = NewDC;
8297 ParentDC && !ParentDC->Equals(OldDC);
8298 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8299 // Only block literals, captured statements, and lambda expressions
8300 // can capture; other scopes don't.
8301 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8302 !isLambdaCallOperator(ParentDC)) {
8303 return;
8304 }
8305 }
8306 }
8307 }
8308 }
8309
8310 // Only warn about certain kinds of shadowing for class members.
8311 if (NewDC && NewDC->isRecord()) {
8312 // In particular, don't warn about shadowing non-class members.
8313 if (!OldDC->isRecord())
8314 return;
8315
8316 // TODO: should we warn about static data members shadowing
8317 // static data members from base classes?
8318
8319 // TODO: don't diagnose for inaccessible shadowed members.
8320 // This is hard to do perfectly because we might friend the
8321 // shadowing context, but that's just a false negative.
8322 }
8323
8324
8325 DeclarationName Name = R.getLookupName();
8326
8327 // Emit warning and note.
8328 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8329 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8330 if (!CaptureLoc.isInvalid())
8331 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8332 << Name << /*explicitly*/ 1;
8333 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8334}
8335
8336/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8337/// when these variables are captured by the lambda.
8339 for (const auto &Shadow : LSI->ShadowingDecls) {
8340 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8341 // Try to avoid the warning when the shadowed decl isn't captured.
8342 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8343 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8344 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8345 ? diag::warn_decl_shadow_uncaptured_local
8346 : diag::warn_decl_shadow)
8347 << Shadow.VD->getDeclName()
8348 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8349 if (!CaptureLoc.isInvalid())
8350 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8351 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8352 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8353 }
8354}
8355
8356/// Check -Wshadow without the advantage of a previous lookup.
8358 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8359 return;
8360
8361 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8363 LookupName(R, S);
8364 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8365 CheckShadow(D, ShadowedDecl, R);
8366}
8367
8368/// Check if 'E', which is an expression that is about to be modified, refers
8369/// to a constructor parameter that shadows a field.
8371 // Quickly ignore expressions that can't be shadowing ctor parameters.
8372 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8373 return;
8374 E = E->IgnoreParenImpCasts();
8375 auto *DRE = dyn_cast<DeclRefExpr>(E);
8376 if (!DRE)
8377 return;
8378 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8379 auto I = ShadowingDecls.find(D);
8380 if (I == ShadowingDecls.end())
8381 return;
8382 const NamedDecl *ShadowedDecl = I->second;
8383 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8384 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8385 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8386 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8387
8388 // Avoid issuing multiple warnings about the same decl.
8389 ShadowingDecls.erase(I);
8390}
8391
8392/// Check for conflict between this global or extern "C" declaration and
8393/// previous global or extern "C" declarations. This is only used in C++.
8394template<typename T>
8396 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8397 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8398 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8399
8400 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8401 // The common case: this global doesn't conflict with any extern "C"
8402 // declaration.
8403 return false;
8404 }
8405
8406 if (Prev) {
8407 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8408 // Both the old and new declarations have C language linkage. This is a
8409 // redeclaration.
8410 Previous.clear();
8411 Previous.addDecl(Prev);
8412 return true;
8413 }
8414
8415 // This is a global, non-extern "C" declaration, and there is a previous
8416 // non-global extern "C" declaration. Diagnose if this is a variable
8417 // declaration.
8418 if (!isa<VarDecl>(ND))
8419 return false;
8420 } else {
8421 // The declaration is extern "C". Check for any declaration in the
8422 // translation unit which might conflict.
8423 if (IsGlobal) {
8424 // We have already performed the lookup into the translation unit.
8425 IsGlobal = false;
8426 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8427 I != E; ++I) {
8428 if (isa<VarDecl>(*I)) {
8429 Prev = *I;
8430 break;
8431 }
8432 }
8433 } else {
8435 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8436 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8437 I != E; ++I) {
8438 if (isa<VarDecl>(*I)) {
8439 Prev = *I;
8440 break;
8441 }
8442 // FIXME: If we have any other entity with this name in global scope,
8443 // the declaration is ill-formed, but that is a defect: it breaks the
8444 // 'stat' hack, for instance. Only variables can have mangled name
8445 // clashes with extern "C" declarations, so only they deserve a
8446 // diagnostic.
8447 }
8448 }
8449
8450 if (!Prev)
8451 return false;
8452 }
8453
8454 // Use the first declaration's location to ensure we point at something which
8455 // is lexically inside an extern "C" linkage-spec.
8456 assert(Prev && "should have found a previous declaration to diagnose");
8457 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8458 Prev = FD->getFirstDecl();
8459 else
8460 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8461
8462 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8463 << IsGlobal << ND;
8464 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8465 << IsGlobal;
8466 return false;
8467}
8468
8469/// Apply special rules for handling extern "C" declarations. Returns \c true
8470/// if we have found that this is a redeclaration of some prior entity.
8471///
8472/// Per C++ [dcl.link]p6:
8473/// Two declarations [for a function or variable] with C language linkage
8474/// with the same name that appear in different scopes refer to the same
8475/// [entity]. An entity with C language linkage shall not be declared with
8476/// the same name as an entity in global scope.
8477template<typename T>
8480 if (!S.getLangOpts().CPlusPlus) {
8481 // In C, when declaring a global variable, look for a corresponding 'extern'
8482 // variable declared in function scope. We don't need this in C++, because
8483 // we find local extern decls in the surrounding file-scope DeclContext.
8484 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8485 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8486 Previous.clear();
8487 Previous.addDecl(Prev);
8488 return true;
8489 }
8490 }
8491 return false;
8492 }
8493
8494 // A declaration in the translation unit can conflict with an extern "C"
8495 // declaration.
8496 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8497 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8498
8499 // An extern "C" declaration can conflict with a declaration in the
8500 // translation unit or can be a redeclaration of an extern "C" declaration
8501 // in another scope.
8502 if (isIncompleteDeclExternC(S,ND))
8503 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8504
8505 // Neither global nor extern "C": nothing to do.
8506 return false;
8507}
8508
8510 // If the decl is already known invalid, don't check it.
8511 if (NewVD->isInvalidDecl())
8512 return;
8513
8514 QualType T = NewVD->getType();
8515
8516 // Defer checking an 'auto' type until its initializer is attached.
8517 if (T->isUndeducedType())
8518 return;
8519
8520 if (NewVD->hasAttrs())
8522
8523 if (T->isObjCObjectType()) {
8524 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8525 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8527 NewVD->setType(T);
8528 }
8529
8530 // Emit an error if an address space was applied to decl with local storage.
8531 // This includes arrays of objects with address space qualifiers, but not
8532 // automatic variables that point to other address spaces.
8533 // ISO/IEC TR 18037 S5.1.2
8534 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8535 T.getAddressSpace() != LangAS::Default) {
8536 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8537 NewVD->setInvalidDecl();
8538 return;
8539 }
8540
8541 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8542 // scope.
8543 if (getLangOpts().OpenCLVersion == 120 &&
8544 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8545 getLangOpts()) &&
8546 NewVD->isStaticLocal()) {
8547 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8548 NewVD->setInvalidDecl();
8549 return;
8550 }
8551
8552 if (getLangOpts().OpenCL) {
8553 if (!diagnoseOpenCLTypes(*this, NewVD))
8554 return;
8555
8556 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8557 if (NewVD->hasAttr<BlocksAttr>()) {
8558 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8559 return;
8560 }
8561
8562 if (T->isBlockPointerType()) {
8563 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8564 // can't use 'extern' storage class.
8565 if (!T.isConstQualified()) {
8566 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8567 << 0 /*const*/;
8568 NewVD->setInvalidDecl();
8569 return;
8570 }
8571 if (NewVD->hasExternalStorage()) {
8572 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8573 NewVD->setInvalidDecl();
8574 return;
8575 }
8576 }
8577
8578 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8579 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8580 NewVD->hasExternalStorage()) {
8581 if (!T->isSamplerT() && !T->isDependentType() &&
8582 !(T.getAddressSpace() == LangAS::opencl_constant ||
8583 (T.getAddressSpace() == LangAS::opencl_global &&
8584 getOpenCLOptions().areProgramScopeVariablesSupported(
8585 getLangOpts())))) {
8586 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8587 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8588 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8589 << Scope << "global or constant";
8590 else
8591 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8592 << Scope << "constant";
8593 NewVD->setInvalidDecl();
8594 return;
8595 }
8596 } else {
8597 if (T.getAddressSpace() == LangAS::opencl_global) {
8598 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8599 << 1 /*is any function*/ << "global";
8600 NewVD->setInvalidDecl();
8601 return;
8602 }
8603 if (T.getAddressSpace() == LangAS::opencl_constant ||
8604 T.getAddressSpace() == LangAS::opencl_local) {
8606 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8607 // in functions.
8608 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8609 if (T.getAddressSpace() == LangAS::opencl_constant)
8610 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8611 << 0 /*non-kernel only*/ << "constant";
8612 else
8613 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8614 << 0 /*non-kernel only*/ << "local";
8615 NewVD->setInvalidDecl();
8616 return;
8617 }
8618 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8619 // in the outermost scope of a kernel function.
8620 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8621 if (!getCurScope()->isFunctionScope()) {
8622 if (T.getAddressSpace() == LangAS::opencl_constant)
8623 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8624 << "constant";
8625 else
8626 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8627 << "local";
8628 NewVD->setInvalidDecl();
8629 return;
8630 }
8631 }
8632 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8633 // If we are parsing a template we didn't deduce an addr
8634 // space yet.
8635 T.getAddressSpace() != LangAS::Default) {
8636 // Do not allow other address spaces on automatic variable.
8637 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8638 NewVD->setInvalidDecl();
8639 return;
8640 }
8641 }
8642 }
8643
8644 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8645 && !NewVD->hasAttr<BlocksAttr>()) {
8646 if (getLangOpts().getGC() != LangOptions::NonGC)
8647 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8648 else {
8649 assert(!getLangOpts().ObjCAutoRefCount);
8650 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8651 }
8652 }
8653
8654 // WebAssembly tables must be static with a zero length and can't be
8655 // declared within functions.
8656 if (T->isWebAssemblyTableType()) {
8657 if (getCurScope()->getParent()) { // Parent is null at top-level
8658 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8659 NewVD->setInvalidDecl();
8660 return;
8661 }
8662 if (NewVD->getStorageClass() != SC_Static) {
8663 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8664 NewVD->setInvalidDecl();
8665 return;
8666 }
8667 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8668 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8669 Diag(NewVD->getLocation(),
8670 diag::err_typecheck_wasm_table_must_have_zero_length);
8671 NewVD->setInvalidDecl();
8672 return;
8673 }
8674 }
8675
8676 bool isVM = T->isVariablyModifiedType();
8677 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8678 NewVD->hasAttr<BlocksAttr>())
8680
8681 if ((isVM && NewVD->hasLinkage()) ||
8682 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8683 bool SizeIsNegative;
8684 llvm::APSInt Oversized;
8686 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8687 QualType FixedT;
8688 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8689 FixedT = FixedTInfo->getType();
8690 else if (FixedTInfo) {
8691 // Type and type-as-written are canonically different. We need to fix up
8692 // both types separately.
8693 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8694 Oversized);
8695 }
8696 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8698 // FIXME: This won't give the correct result for
8699 // int a[10][n];
8700 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8701
8702 if (NewVD->isFileVarDecl())
8703 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8704 << SizeRange;
8705 else if (NewVD->isStaticLocal())
8706 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8707 << SizeRange;
8708 else
8709 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8710 << SizeRange;
8711 NewVD->setInvalidDecl();
8712 return;
8713 }
8714
8715 if (!FixedTInfo) {
8716 if (NewVD->isFileVarDecl())
8717 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8718 else
8719 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8720 NewVD->setInvalidDecl();
8721 return;
8722 }
8723
8724 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8725 NewVD->setType(FixedT);
8726 NewVD->setTypeSourceInfo(FixedTInfo);
8727 }
8728
8729 if (T->isVoidType()) {
8730 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8731 // of objects and functions.
8733 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8734 << T;
8735 NewVD->setInvalidDecl();
8736 return;
8737 }
8738 }
8739
8740 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8741 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8742 NewVD->setInvalidDecl();
8743 return;
8744 }
8745
8746 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8747 !T.isWebAssemblyReferenceType()) {
8748 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8749 NewVD->setInvalidDecl();
8750 return;
8751 }
8752
8753 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8754 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8755 NewVD->setInvalidDecl();
8756 return;
8757 }
8758
8759 if (NewVD->isConstexpr() && !T->isDependentType() &&
8760 RequireLiteralType(NewVD->getLocation(), T,
8761 diag::err_constexpr_var_non_literal)) {
8762 NewVD->setInvalidDecl();
8763 return;
8764 }
8765
8766 // PPC MMA non-pointer types are not allowed as non-local variable types.
8767 if (Context.getTargetInfo().getTriple().isPPC64() &&
8768 !NewVD->isLocalVarDecl() &&
8769 CheckPPCMMAType(T, NewVD->getLocation())) {
8770 NewVD->setInvalidDecl();
8771 return;
8772 }
8773
8774 // Check that SVE types are only used in functions with SVE available.
8775 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8777 llvm::StringMap<bool> CallerFeatureMap;
8778 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8780 "sve", CallerFeatureMap)) {
8781 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8782 NewVD->setInvalidDecl();
8783 return;
8784 }
8785 }
8786
8787 if (T->isRVVType())
8788 checkRVVTypeSupport(T, NewVD->getLocation(), cast<ValueDecl>(CurContext));
8789}
8790
8791/// Perform semantic checking on a newly-created variable
8792/// declaration.
8793///
8794/// This routine performs all of the type-checking required for a
8795/// variable declaration once it has been built. It is used both to
8796/// check variables after they have been parsed and their declarators
8797/// have been translated into a declaration, and to check variables
8798/// that have been instantiated from a template.
8799///
8800/// Sets NewVD->isInvalidDecl() if an error was encountered.
8801///
8802/// Returns true if the variable declaration is a redeclaration.
8805
8806 // If the decl is already known invalid, don't check it.
8807 if (NewVD->isInvalidDecl())
8808 return false;
8809
8810 // If we did not find anything by this name, look for a non-visible
8811 // extern "C" declaration with the same name.
8812 if (Previous.empty() &&
8814 Previous.setShadowed();
8815
8816 if (!Previous.empty()) {
8817 MergeVarDecl(NewVD, Previous);
8818 return true;
8819 }
8820 return false;
8821}
8822
8823/// AddOverriddenMethods - See if a method overrides any in the base classes,
8824/// and if so, check that it's a valid override and remember it.
8827
8828 // Look for methods in base classes that this method might override.
8829 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8830 /*DetectVirtual=*/false);
8831 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8832 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8833 DeclarationName Name = MD->getDeclName();
8834
8835 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8836 // We really want to find the base class destructor here.
8837 QualType T = Context.getTypeDeclType(BaseRecord);
8840 }
8841
8842 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8843 CXXMethodDecl *BaseMD =
8844 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8845 if (!BaseMD || !BaseMD->isVirtual() ||
8846 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8847 /*ConsiderCudaAttrs=*/true,
8848 // C++2a [class.virtual]p2 does not consider requires
8849 // clauses when overriding.
8850 /*ConsiderRequiresClauses=*/false))
8851 continue;
8852
8853 if (Overridden.insert(BaseMD).second) {
8854 MD->addOverriddenMethod(BaseMD);
8859 }
8860
8861 // A method can only override one function from each base class. We
8862 // don't track indirectly overridden methods from bases of bases.
8863 return true;
8864 }
8865
8866 return false;
8867 };
8868
8869 DC->lookupInBases(VisitBase, Paths);
8870 return !Overridden.empty();
8871}
8872
8873namespace {
8874 // Struct for holding all of the extra arguments needed by
8875 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8876 struct ActOnFDArgs {
8877 Scope *S;
8878 Declarator &D;
8879 MultiTemplateParamsArg TemplateParamLists;
8880 bool AddToScope;
8881 };
8882} // end anonymous namespace
8883
8884namespace {
8885
8886// Callback to only accept typo corrections that have a non-zero edit distance.
8887// Also only accept corrections that have the same parent decl.
8888class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8889 public:
8890 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8892 : Context(Context), OriginalFD(TypoFD),
8893 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8894
8895 bool ValidateCandidate(const TypoCorrection &candidate) override {
8896 if (candidate.getEditDistance() == 0)
8897 return false;
8898
8899 SmallVector<unsigned, 1> MismatchedParams;
8900 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8901 CDeclEnd = candidate.end();
8902 CDecl != CDeclEnd; ++CDecl) {
8903 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8904
8905 if (FD && !FD->hasBody() &&
8906 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8907 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8909 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8910 return true;
8911 } else if (!ExpectedParent) {
8912 return true;
8913 }
8914 }
8915 }
8916
8917 return false;
8918 }
8919
8920 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8921 return std::make_unique<DifferentNameValidatorCCC>(*this);
8922 }
8923
8924 private:
8925 ASTContext &Context;
8926 FunctionDecl *OriginalFD;
8927 CXXRecordDecl *ExpectedParent;
8928};
8929
8930} // end anonymous namespace
8931
8935
8936/// Generate diagnostics for an invalid function redeclaration.
8937///
8938/// This routine handles generating the diagnostic messages for an invalid
8939/// function redeclaration, including finding possible similar declarations
8940/// or performing typo correction if there are no previous declarations with
8941/// the same name.
8942///
8943/// Returns a NamedDecl iff typo correction was performed and substituting in
8944/// the new declaration name does not cause new errors.
8946 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8947 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8948 DeclarationName Name = NewFD->getDeclName();
8949 DeclContext *NewDC = NewFD->getDeclContext();
8950 SmallVector<unsigned, 1> MismatchedParams;
8952 TypoCorrection Correction;
8953 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8954 unsigned DiagMsg =
8955 IsLocalFriend ? diag::err_no_matching_local_friend :
8956 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8957 diag::err_member_decl_does_not_match;
8958 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8959 IsLocalFriend ? Sema::LookupLocalFriendName
8962
8963 NewFD->setInvalidDecl();
8964 if (IsLocalFriend)
8965 SemaRef.LookupName(Prev, S);
8966 else
8967 SemaRef.LookupQualifiedName(Prev, NewDC);
8968 assert(!Prev.isAmbiguous() &&
8969 "Cannot have an ambiguity in previous-declaration lookup");
8970 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8971 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8972 MD ? MD->getParent() : nullptr);
8973 if (!Prev.empty()) {
8974 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8975 Func != FuncEnd; ++Func) {
8976 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8977 if (FD &&
8978 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8979 // Add 1 to the index so that 0 can mean the mismatch didn't
8980 // involve a parameter
8981 unsigned ParamNum =
8982 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8983 NearMatches.push_back(std::make_pair(FD, ParamNum));
8984 }
8985 }
8986 // If the qualified name lookup yielded nothing, try typo correction
8987 } else if ((Correction = SemaRef.CorrectTypo(
8988 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8989 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8990 IsLocalFriend ? nullptr : NewDC))) {
8991 // Set up everything for the call to ActOnFunctionDeclarator
8992 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8993 ExtraArgs.D.getIdentifierLoc());
8994 Previous.clear();
8995 Previous.setLookupName(Correction.getCorrection());
8996 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8997 CDeclEnd = Correction.end();
8998 CDecl != CDeclEnd; ++CDecl) {
8999 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9000 if (FD && !FD->hasBody() &&
9001 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9002 Previous.addDecl(FD);
9003 }
9004 }
9005 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9006
9008 // Retry building the function declaration with the new previous
9009 // declarations, and with errors suppressed.
9010 {
9011 // Trap errors.
9012 Sema::SFINAETrap Trap(SemaRef);
9013
9014 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9015 // pieces need to verify the typo-corrected C++ declaration and hopefully
9016 // eliminate the need for the parameter pack ExtraArgs.
9018 ExtraArgs.S, ExtraArgs.D,
9019 Correction.getCorrectionDecl()->getDeclContext(),
9020 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9021 ExtraArgs.AddToScope);
9022
9023 if (Trap.hasErrorOccurred())
9024 Result = nullptr;
9025 }
9026
9027 if (Result) {
9028 // Determine which correction we picked.
9029 Decl *Canonical = Result->getCanonicalDecl();
9030 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9031 I != E; ++I)
9032 if ((*I)->getCanonicalDecl() == Canonical)
9033 Correction.setCorrectionDecl(*I);
9034
9035 // Let Sema know about the correction.
9037 SemaRef.diagnoseTypo(
9038 Correction,
9039 SemaRef.PDiag(IsLocalFriend
9040 ? diag::err_no_matching_local_friend_suggest
9041 : diag::err_member_decl_does_not_match_suggest)
9042 << Name << NewDC << IsDefinition);
9043 return Result;
9044 }
9045
9046 // Pretend the typo correction never occurred
9047 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9048 ExtraArgs.D.getIdentifierLoc());
9049 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9050 Previous.clear();
9051 Previous.setLookupName(Name);
9052 }
9053
9054 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9055 << Name << NewDC << IsDefinition << NewFD->getLocation();
9056
9057 bool NewFDisConst = false;
9058 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9059 NewFDisConst = NewMD->isConst();
9060
9061 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9062 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9063 NearMatch != NearMatchEnd; ++NearMatch) {
9064 FunctionDecl *FD = NearMatch->first;
9065 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9066 bool FDisConst = MD && MD->isConst();
9067 bool IsMember = MD || !IsLocalFriend;
9068
9069 // FIXME: These notes are poorly worded for the local friend case.
9070 if (unsigned Idx = NearMatch->second) {
9071 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9072 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9073 if (Loc.isInvalid()) Loc = FD->getLocation();
9074 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9075 : diag::note_local_decl_close_param_match)
9076 << Idx << FDParam->getType()
9077 << NewFD->getParamDecl(Idx - 1)->getType();
9078 } else if (FDisConst != NewFDisConst) {
9079 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9080 << NewFDisConst << FD->getSourceRange().getEnd()
9081 << (NewFDisConst
9085 .getRParenLoc()
9086 .getLocWithOffset(1),
9087 " const"));
9088 } else
9089 SemaRef.Diag(FD->getLocation(),
9090 IsMember ? diag::note_member_def_close_match
9091 : diag::note_local_decl_close_match);
9092 }
9093 return nullptr;
9094}
9095
9097 switch (D.getDeclSpec().getStorageClassSpec()) {
9098 default: llvm_unreachable("Unknown storage class!");
9099 case DeclSpec::SCS_auto:
9103 diag::err_typecheck_sclass_func);
9105 D.setInvalidType();
9106 break;
9107 case DeclSpec::SCS_unspecified: break;
9110 return SC_None;
9111 return SC_Extern;
9112 case DeclSpec::SCS_static: {
9114 // C99 6.7.1p5:
9115 // The declaration of an identifier for a function that has
9116 // block scope shall have no explicit storage-class specifier
9117 // other than extern
9118 // See also (C++ [dcl.stc]p4).
9120 diag::err_static_block_func);
9121 break;
9122 } else
9123 return SC_Static;
9124 }
9126 }
9127
9128 // No explicit storage class has already been returned
9129 return SC_None;
9130}
9131
9133 DeclContext *DC, QualType &R,
9134 TypeSourceInfo *TInfo,
9135 StorageClass SC,
9136 bool &IsVirtualOkay) {
9137 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9138 DeclarationName Name = NameInfo.getName();
9139
9140 FunctionDecl *NewFD = nullptr;
9141 bool isInline = D.getDeclSpec().isInlineSpecified();
9142
9143 if (!SemaRef.getLangOpts().CPlusPlus) {
9144 // Determine whether the function was written with a prototype. This is
9145 // true when:
9146 // - there is a prototype in the declarator, or
9147 // - the type R of the function is some kind of typedef or other non-
9148 // attributed reference to a type name (which eventually refers to a
9149 // function type). Note, we can't always look at the adjusted type to
9150 // check this case because attributes may cause a non-function
9151 // declarator to still have a function type. e.g.,
9152 // typedef void func(int a);
9153 // __attribute__((noreturn)) func other_func; // This has a prototype
9154 bool HasPrototype =
9156 (D.getDeclSpec().isTypeRep() &&
9157 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9158 ->isFunctionProtoType()) ||
9160 assert(
9161 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9162 "Strict prototypes are required");
9163
9164 NewFD = FunctionDecl::Create(
9165 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9166 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9168 /*TrailingRequiresClause=*/nullptr);
9169 if (D.isInvalidType())
9170 NewFD->setInvalidDecl();
9171
9172 return NewFD;
9173 }
9174
9176
9178 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9179 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9180 diag::err_constexpr_wrong_decl_kind)
9181 << static_cast<int>(ConstexprKind);
9182 ConstexprKind = ConstexprSpecKind::Unspecified;
9184 }
9185 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9186
9187 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9188 // This is a C++ constructor declaration.
9189 assert(DC->isRecord() &&
9190 "Constructors can only be declared in a member context");
9191
9192 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9194 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9196 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9197 InheritedConstructor(), TrailingRequiresClause);
9198
9199 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9200 // This is a C++ destructor declaration.
9201 if (DC->isRecord()) {
9202 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9203 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9205 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9206 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9207 /*isImplicitlyDeclared=*/false, ConstexprKind,
9208 TrailingRequiresClause);
9209 // User defined destructors start as not selected if the class definition is still
9210 // not done.
9211 if (Record->isBeingDefined())
9212 NewDD->setIneligibleOrNotSelected(true);
9213
9214 // If the destructor needs an implicit exception specification, set it
9215 // now. FIXME: It'd be nice to be able to create the right type to start
9216 // with, but the type needs to reference the destructor declaration.
9217 if (SemaRef.getLangOpts().CPlusPlus11)
9218 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9219
9220 IsVirtualOkay = true;
9221 return NewDD;
9222
9223 } else {
9224 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9225 D.setInvalidType();
9226
9227 // Create a FunctionDecl to satisfy the function definition parsing
9228 // code path.
9229 return FunctionDecl::Create(
9230 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9231 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9232 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9233 }
9234
9235 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9236 if (!DC->isRecord()) {
9237 SemaRef.Diag(D.getIdentifierLoc(),
9238 diag::err_conv_function_not_member);
9239 return nullptr;
9240 }
9241
9242 SemaRef.CheckConversionDeclarator(D, R, SC);
9243 if (D.isInvalidType())
9244 return nullptr;
9245
9246 IsVirtualOkay = true;
9248 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9249 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9250 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9251 TrailingRequiresClause);
9252
9253 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9254 if (TrailingRequiresClause)
9255 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9256 diag::err_trailing_requires_clause_on_deduction_guide)
9257 << TrailingRequiresClause->getSourceRange();
9258 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9259 return nullptr;
9260 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9261 ExplicitSpecifier, NameInfo, R, TInfo,
9262 D.getEndLoc());
9263 } else if (DC->isRecord()) {
9264 // If the name of the function is the same as the name of the record,
9265 // then this must be an invalid constructor that has a return type.
9266 // (The parser checks for a return type and makes the declarator a
9267 // constructor if it has no return type).
9268 if (Name.getAsIdentifierInfo() &&
9269 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9270 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9273 return nullptr;
9274 }
9275
9276 // This is a C++ method declaration.
9278 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9279 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9280 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9281 IsVirtualOkay = !Ret->isStatic();
9282 return Ret;
9283 } else {
9284 bool isFriend =
9285 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9286 if (!isFriend && SemaRef.CurContext->isRecord())
9287 return nullptr;
9288
9289 // Determine whether the function was written with a
9290 // prototype. This true when:
9291 // - we're in C++ (where every function has a prototype),
9292 return FunctionDecl::Create(
9293 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9294 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9295 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9296 }
9297}
9298
9307
9309 // Size dependent types are just typedefs to normal integer types
9310 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9311 // integers other than by their names.
9312 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9313
9314 // Remove typedefs one by one until we reach a typedef
9315 // for a size dependent type.
9316 QualType DesugaredTy = Ty;
9317 do {
9318 ArrayRef<StringRef> Names(SizeTypeNames);
9319 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9320 if (Names.end() != Match)
9321 return true;
9322
9323 Ty = DesugaredTy;
9324 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9325 } while (DesugaredTy != Ty);
9326
9327 return false;
9328}
9329
9331 if (PT->isDependentType())
9332 return InvalidKernelParam;
9333
9334 if (PT->isPointerType() || PT->isReferenceType()) {
9335 QualType PointeeType = PT->getPointeeType();
9336 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9337 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9338 PointeeType.getAddressSpace() == LangAS::Default)
9340
9341 if (PointeeType->isPointerType()) {
9342 // This is a pointer to pointer parameter.
9343 // Recursively check inner type.
9344 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9345 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9346 ParamKind == InvalidKernelParam)
9347 return ParamKind;
9348
9349 // OpenCL v3.0 s6.11.a:
9350 // A restriction to pass pointers to pointers only applies to OpenCL C
9351 // v1.2 or below.
9353 return ValidKernelParam;
9354
9355 return PtrPtrKernelParam;
9356 }
9357
9358 // C++ for OpenCL v1.0 s2.4:
9359 // Moreover the types used in parameters of the kernel functions must be:
9360 // Standard layout types for pointer parameters. The same applies to
9361 // reference if an implementation supports them in kernel parameters.
9362 if (S.getLangOpts().OpenCLCPlusPlus &&
9364 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9365 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9366 bool IsStandardLayoutType = true;
9367 if (CXXRec) {
9368 // If template type is not ODR-used its definition is only available
9369 // in the template definition not its instantiation.
9370 // FIXME: This logic doesn't work for types that depend on template
9371 // parameter (PR58590).
9372 if (!CXXRec->hasDefinition())
9373 CXXRec = CXXRec->getTemplateInstantiationPattern();
9374 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9375 IsStandardLayoutType = false;
9376 }
9377 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9378 !IsStandardLayoutType)
9379 return InvalidKernelParam;
9380 }
9381
9382 // OpenCL v1.2 s6.9.p:
9383 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9385 return ValidKernelParam;
9386
9387 return PtrKernelParam;
9388 }
9389
9390 // OpenCL v1.2 s6.9.k:
9391 // Arguments to kernel functions in a program cannot be declared with the
9392 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9393 // uintptr_t or a struct and/or union that contain fields declared to be one
9394 // of these built-in scalar types.
9396 return InvalidKernelParam;
9397
9398 if (PT->isImageType())
9399 return PtrKernelParam;
9400
9401 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9402 return InvalidKernelParam;
9403
9404 // OpenCL extension spec v1.2 s9.5:
9405 // This extension adds support for half scalar and vector types as built-in
9406 // types that can be used for arithmetic operations, conversions etc.
9407 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9408 PT->isHalfType())
9409 return InvalidKernelParam;
9410
9411 // Look into an array argument to check if it has a forbidden type.
9412 if (PT->isArrayType()) {
9413 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9414 // Call ourself to check an underlying type of an array. Since the
9415 // getPointeeOrArrayElementType returns an innermost type which is not an
9416 // array, this recursive call only happens once.
9417 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9418 }
9419
9420 // C++ for OpenCL v1.0 s2.4:
9421 // Moreover the types used in parameters of the kernel functions must be:
9422 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9423 // types) for parameters passed by value;
9424 if (S.getLangOpts().OpenCLCPlusPlus &&
9426 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9427 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9428 return InvalidKernelParam;
9429
9430 if (PT->isRecordType())
9431 return RecordKernelParam;
9432
9433 return ValidKernelParam;
9434}
9435
9437 Sema &S,
9438 Declarator &D,
9439 ParmVarDecl *Param,
9440 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9441 QualType PT = Param->getType();
9442
9443 // Cache the valid types we encounter to avoid rechecking structs that are
9444 // used again
9445 if (ValidTypes.count(PT.getTypePtr()))
9446 return;
9447
9448 switch (getOpenCLKernelParameterType(S, PT)) {
9449 case PtrPtrKernelParam:
9450 // OpenCL v3.0 s6.11.a:
9451 // A kernel function argument cannot be declared as a pointer to a pointer
9452 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9453 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9454 D.setInvalidType();
9455 return;
9456
9458 // OpenCL v1.0 s6.5:
9459 // __kernel function arguments declared to be a pointer of a type can point
9460 // to one of the following address spaces only : __global, __local or
9461 // __constant.
9462 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9463 D.setInvalidType();
9464 return;
9465
9466 // OpenCL v1.2 s6.9.k:
9467 // Arguments to kernel functions in a program cannot be declared with the
9468 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9469 // uintptr_t or a struct and/or union that contain fields declared to be
9470 // one of these built-in scalar types.
9471
9472 case InvalidKernelParam:
9473 // OpenCL v1.2 s6.8 n:
9474 // A kernel function argument cannot be declared
9475 // of event_t type.
9476 // Do not diagnose half type since it is diagnosed as invalid argument
9477 // type for any function elsewhere.
9478 if (!PT->isHalfType()) {
9479 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9480
9481 // Explain what typedefs are involved.
9482 const TypedefType *Typedef = nullptr;
9483 while ((Typedef = PT->getAs<TypedefType>())) {
9484 SourceLocation Loc = Typedef->getDecl()->getLocation();
9485 // SourceLocation may be invalid for a built-in type.
9486 if (Loc.isValid())
9487 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9488 PT = Typedef->desugar();
9489 }
9490 }
9491
9492 D.setInvalidType();
9493 return;
9494
9495 case PtrKernelParam:
9496 case ValidKernelParam:
9497 ValidTypes.insert(PT.getTypePtr());
9498 return;
9499
9500 case RecordKernelParam:
9501 break;
9502 }
9503
9504 // Track nested structs we will inspect
9506
9507 // Track where we are in the nested structs. Items will migrate from
9508 // VisitStack to HistoryStack as we do the DFS for bad field.
9510 HistoryStack.push_back(nullptr);
9511
9512 // At this point we already handled everything except of a RecordType or
9513 // an ArrayType of a RecordType.
9514 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9515 const RecordType *RecTy =
9516 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9517 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9518
9519 VisitStack.push_back(RecTy->getDecl());
9520 assert(VisitStack.back() && "First decl null?");
9521
9522 do {
9523 const Decl *Next = VisitStack.pop_back_val();
9524 if (!Next) {
9525 assert(!HistoryStack.empty());
9526 // Found a marker, we have gone up a level
9527 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9528 ValidTypes.insert(Hist->getType().getTypePtr());
9529
9530 continue;
9531 }
9532
9533 // Adds everything except the original parameter declaration (which is not a
9534 // field itself) to the history stack.
9535 const RecordDecl *RD;
9536 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9537 HistoryStack.push_back(Field);
9538
9539 QualType FieldTy = Field->getType();
9540 // Other field types (known to be valid or invalid) are handled while we
9541 // walk around RecordDecl::fields().
9542 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9543 "Unexpected type.");
9544 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9545
9546 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9547 } else {
9548 RD = cast<RecordDecl>(Next);
9549 }
9550
9551 // Add a null marker so we know when we've gone back up a level
9552 VisitStack.push_back(nullptr);
9553
9554 for (const auto *FD : RD->fields()) {
9555 QualType QT = FD->getType();
9556
9557 if (ValidTypes.count(QT.getTypePtr()))
9558 continue;
9559
9561 if (ParamType == ValidKernelParam)
9562 continue;
9563
9564 if (ParamType == RecordKernelParam) {
9565 VisitStack.push_back(FD);
9566 continue;
9567 }
9568
9569 // OpenCL v1.2 s6.9.p:
9570 // Arguments to kernel functions that are declared to be a struct or union
9571 // do not allow OpenCL objects to be passed as elements of the struct or
9572 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9573 // of SVM.
9574 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9575 ParamType == InvalidAddrSpacePtrKernelParam) {
9576 S.Diag(Param->getLocation(),
9577 diag::err_record_with_pointers_kernel_param)
9578 << PT->isUnionType()
9579 << PT;
9580 } else {
9581 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9582 }
9583
9584 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9585 << OrigRecDecl->getDeclName();
9586
9587 // We have an error, now let's go back up through history and show where
9588 // the offending field came from
9590 I = HistoryStack.begin() + 1,
9591 E = HistoryStack.end();
9592 I != E; ++I) {
9593 const FieldDecl *OuterField = *I;
9594 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9595 << OuterField->getType();
9596 }
9597
9598 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9599 << QT->isPointerType()
9600 << QT;
9601 D.setInvalidType();
9602 return;
9603 }
9604 } while (!VisitStack.empty());
9605}
9606
9607/// Find the DeclContext in which a tag is implicitly declared if we see an
9608/// elaborated type specifier in the specified context, and lookup finds
9609/// nothing.
9611 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9612 DC = DC->getParent();
9613 return DC;
9614}
9615
9616/// Find the Scope in which a tag is implicitly declared if we see an
9617/// elaborated type specifier in the specified context, and lookup finds
9618/// nothing.
9619static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9620 while (S->isClassScope() ||
9621 (LangOpts.CPlusPlus &&
9622 S->isFunctionPrototypeScope()) ||
9623 ((S->getFlags() & Scope::DeclScope) == 0) ||
9624 (S->getEntity() && S->getEntity()->isTransparentContext()))
9625 S = S->getParent();
9626 return S;
9627}
9628
9629/// Determine whether a declaration matches a known function in namespace std.
9631 unsigned BuiltinID) {
9632 switch (BuiltinID) {
9633 case Builtin::BI__GetExceptionInfo:
9634 // No type checking whatsoever.
9635 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9636
9637 case Builtin::BIaddressof:
9638 case Builtin::BI__addressof:
9639 case Builtin::BIforward:
9640 case Builtin::BIforward_like:
9641 case Builtin::BImove:
9642 case Builtin::BImove_if_noexcept:
9643 case Builtin::BIas_const: {
9644 // Ensure that we don't treat the algorithm
9645 // OutputIt std::move(InputIt, InputIt, OutputIt)
9646 // as the builtin std::move.
9647 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9648 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9649 }
9650
9651 default:
9652 return false;
9653 }
9654}
9655
9656NamedDecl*
9659 MultiTemplateParamsArg TemplateParamListsRef,
9660 bool &AddToScope) {
9661 QualType R = TInfo->getType();
9662
9663 assert(R->isFunctionType());
9665 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9666
9667 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9668 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9670 if (!TemplateParamLists.empty() &&
9671 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9672 TemplateParamLists.back() = Invented;
9673 else
9674 TemplateParamLists.push_back(Invented);
9675 }
9676
9677 // TODO: consider using NameInfo for diagnostic.
9679 DeclarationName Name = NameInfo.getName();
9681
9684 diag::err_invalid_thread)
9686
9689 D.getIdentifierLoc());
9690
9691 bool isFriend = false;
9693 bool isMemberSpecialization = false;
9694 bool isFunctionTemplateSpecialization = false;
9695
9696 bool isDependentClassScopeExplicitSpecialization = false;
9697 bool HasExplicitTemplateArgs = false;
9698 TemplateArgumentListInfo TemplateArgs;
9699
9700 bool isVirtualOkay = false;
9701
9702 DeclContext *OriginalDC = DC;
9703 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9704
9705 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9706 isVirtualOkay);
9707 if (!NewFD) return nullptr;
9708
9711
9712 // Set the lexical context. If this is a function-scope declaration, or has a
9713 // C++ scope specifier, or is the object of a friend declaration, the lexical
9714 // context will be different from the semantic context.
9716
9717 if (IsLocalExternDecl)
9718 NewFD->setLocalExternDecl();
9719
9720 if (getLangOpts().CPlusPlus) {
9721 // The rules for implicit inlines changed in C++20 for methods and friends
9722 // with an in-class definition (when such a definition is not attached to
9723 // the global module). User-specified 'inline' overrides this (set when
9724 // the function decl is created above).
9725 // FIXME: We need a better way to separate C++ standard and clang modules.
9726 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9727 !NewFD->getOwningModule() ||
9728 NewFD->getOwningModule()->isGlobalModule() ||
9730 bool isInline = D.getDeclSpec().isInlineSpecified();
9731 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9732 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9733 isFriend = D.getDeclSpec().isFriendSpecified();
9734 if (isFriend && !isInline && D.isFunctionDefinition()) {
9735 // Pre-C++20 [class.friend]p5
9736 // A function can be defined in a friend declaration of a
9737 // class . . . . Such a function is implicitly inline.
9738 // Post C++20 [class.friend]p7
9739 // Such a function is implicitly an inline function if it is attached
9740 // to the global module.
9741 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9742 }
9743
9744 // If this is a method defined in an __interface, and is not a constructor
9745 // or an overloaded operator, then set the pure flag (isVirtual will already
9746 // return true).
9747 if (const CXXRecordDecl *Parent =
9748 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9749 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9750 NewFD->setPure(true);
9751
9752 // C++ [class.union]p2
9753 // A union can have member functions, but not virtual functions.
9754 if (isVirtual && Parent->isUnion()) {
9755 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9756 NewFD->setInvalidDecl();
9757 }
9758 if ((Parent->isClass() || Parent->isStruct()) &&
9759 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9760 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9761 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9762 if (auto *Def = Parent->getDefinition())
9763 Def->setInitMethod(true);
9764 }
9765 }
9766
9767 SetNestedNameSpecifier(*this, NewFD, D);
9768 isMemberSpecialization = false;
9769 isFunctionTemplateSpecialization = false;
9770 if (D.isInvalidType())
9771 NewFD->setInvalidDecl();
9772
9773 // Match up the template parameter lists with the scope specifier, then
9774 // determine whether we have a template or a template specialization.
9775 bool Invalid = false;
9776 TemplateParameterList *TemplateParams =
9779 D.getCXXScopeSpec(),
9781 ? D.getName().TemplateId
9782 : nullptr,
9783 TemplateParamLists, isFriend, isMemberSpecialization,
9784 Invalid);
9785 if (TemplateParams) {
9786 // Check that we can declare a template here.
9787 if (CheckTemplateDeclScope(S, TemplateParams))
9788 NewFD->setInvalidDecl();
9789
9790 if (TemplateParams->size() > 0) {
9791 // This is a function template
9792
9793 // A destructor cannot be a template.
9794 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9795 Diag(NewFD->getLocation(), diag::err_destructor_template);
9796 NewFD->setInvalidDecl();
9797 }
9798
9799 // If we're adding a template to a dependent context, we may need to
9800 // rebuilding some of the types used within the template parameter list,
9801 // now that we know what the current instantiation is.
9802 if (DC->isDependentContext()) {
9803 ContextRAII SavedContext(*this, DC);
9805 Invalid = true;
9806 }
9807
9809 NewFD->getLocation(),
9810 Name, TemplateParams,
9811 NewFD);
9812 FunctionTemplate->setLexicalDeclContext(CurContext);
9814
9815 // For source fidelity, store the other template param lists.
9816 if (TemplateParamLists.size() > 1) {
9818 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9819 .drop_back(1));
9820 }
9821 } else {
9822 // This is a function template specialization.
9823 isFunctionTemplateSpecialization = true;
9824 // For source fidelity, store all the template param lists.
9825 if (TemplateParamLists.size() > 0)
9826 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9827
9828 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9829 if (isFriend) {
9830 // We want to remove the "template<>", found here.
9831 SourceRange RemoveRange = TemplateParams->getSourceRange();
9832
9833 // If we remove the template<> and the name is not a
9834 // template-id, we're actually silently creating a problem:
9835 // the friend declaration will refer to an untemplated decl,
9836 // and clearly the user wants a template specialization. So
9837 // we need to insert '<>' after the name.
9838 SourceLocation InsertLoc;
9840 InsertLoc = D.getName().getSourceRange().getEnd();
9841 InsertLoc = getLocForEndOfToken(InsertLoc);
9842 }
9843
9844 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9845 << Name << RemoveRange
9846 << FixItHint::CreateRemoval(RemoveRange)
9847 << FixItHint::CreateInsertion(InsertLoc, "<>");
9848 Invalid = true;
9849 }
9850 }
9851 } else {
9852 // Check that we can declare a template here.
9853 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9854 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9855 NewFD->setInvalidDecl();
9856
9857 // All template param lists were matched against the scope specifier:
9858 // this is NOT (an explicit specialization of) a template.
9859 if (TemplateParamLists.size() > 0)
9860 // For source fidelity, store all the template param lists.
9861 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9862 }
9863
9864 if (Invalid) {
9865 NewFD->setInvalidDecl();
9866 if (FunctionTemplate)
9867 FunctionTemplate->setInvalidDecl();
9868 }
9869
9870 // C++ [dcl.fct.spec]p5:
9871 // The virtual specifier shall only be used in declarations of
9872 // nonstatic class member functions that appear within a
9873 // member-specification of a class declaration; see 10.3.
9874 //
9875 if (isVirtual && !NewFD->isInvalidDecl()) {
9876 if (!isVirtualOkay) {
9878 diag::err_virtual_non_function);
9879 } else if (!CurContext->isRecord()) {
9880 // 'virtual' was specified outside of the class.
9882 diag::err_virtual_out_of_class)
9884 } else if (NewFD->getDescribedFunctionTemplate()) {
9885 // C++ [temp.mem]p3:
9886 // A member function template shall not be virtual.
9888 diag::err_virtual_member_function_template)
9890 } else {
9891 // Okay: Add virtual to the method.
9892 NewFD->setVirtualAsWritten(true);
9893 }
9894
9895 if (getLangOpts().CPlusPlus14 &&
9896 NewFD->getReturnType()->isUndeducedType())
9897 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9898 }
9899
9900 if (getLangOpts().CPlusPlus14 &&
9901 (NewFD->isDependentContext() ||
9902 (isFriend && CurContext->isDependentContext())) &&
9903 NewFD->getReturnType()->isUndeducedType()) {
9904 // If the function template is referenced directly (for instance, as a
9905 // member of the current instantiation), pretend it has a dependent type.
9906 // This is not really justified by the standard, but is the only sane
9907 // thing to do.
9908 // FIXME: For a friend function, we have not marked the function as being
9909 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9910 const FunctionProtoType *FPT =
9911 NewFD->getType()->castAs<FunctionProtoType>();
9914 FPT->getExtProtoInfo()));
9915 }
9916
9917 // C++ [dcl.fct.spec]p3:
9918 // The inline specifier shall not appear on a block scope function
9919 // declaration.
9920 if (isInline && !NewFD->isInvalidDecl()) {
9922 // 'inline' is not allowed on block scope function declaration.
9924 diag::err_inline_declaration_block_scope) << Name
9926 }
9927 }
9928
9929 // C++ [dcl.fct.spec]p6:
9930 // The explicit specifier shall be used only in the declaration of a
9931 // constructor or conversion function within its class definition;
9932 // see 12.3.1 and 12.3.2.
9933 if (hasExplicit && !NewFD->isInvalidDecl() &&
9934 !isa<CXXDeductionGuideDecl>(NewFD)) {
9935 if (!CurContext->isRecord()) {
9936 // 'explicit' was specified outside of the class.
9938 diag::err_explicit_out_of_class)
9940 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9941 !isa<CXXConversionDecl>(NewFD)) {
9942 // 'explicit' was specified on a function that wasn't a constructor
9943 // or conversion function.
9945 diag::err_explicit_non_ctor_or_conv_function)
9947 }
9948 }
9949
9951 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9952 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9953 // are implicitly inline.
9954 NewFD->setImplicitlyInline();
9955
9956 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9957 // be either constructors or to return a literal type. Therefore,
9958 // destructors cannot be declared constexpr.
9959 if (isa<CXXDestructorDecl>(NewFD) &&
9961 ConstexprKind == ConstexprSpecKind::Consteval)) {
9962 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9963 << static_cast<int>(ConstexprKind);
9967 }
9968 // C++20 [dcl.constexpr]p2: An allocation function, or a
9969 // deallocation function shall not be declared with the consteval
9970 // specifier.
9971 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9972 (NewFD->getOverloadedOperator() == OO_New ||
9973 NewFD->getOverloadedOperator() == OO_Array_New ||
9974 NewFD->getOverloadedOperator() == OO_Delete ||
9975 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9977 diag::err_invalid_consteval_decl_kind)
9978 << NewFD;
9980 }
9981 }
9982
9983 // If __module_private__ was specified, mark the function accordingly.
9985 if (isFunctionTemplateSpecialization) {
9986 SourceLocation ModulePrivateLoc
9988 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9989 << 0
9990 << FixItHint::CreateRemoval(ModulePrivateLoc);
9991 } else {
9992 NewFD->setModulePrivate();
9993 if (FunctionTemplate)
9994 FunctionTemplate->setModulePrivate();
9995 }
9996 }
9997
9998 if (isFriend) {
9999 if (FunctionTemplate) {
10000 FunctionTemplate->setObjectOfFriendDecl();
10001 FunctionTemplate->setAccess(AS_public);
10002 }
10003 NewFD->setObjectOfFriendDecl();
10004 NewFD->setAccess(AS_public);
10005 }
10006
10007 // If a function is defined as defaulted or deleted, mark it as such now.
10008 // We'll do the relevant checks on defaulted / deleted functions later.
10009 switch (D.getFunctionDefinitionKind()) {
10012 break;
10013
10015 NewFD->setDefaulted();
10016 break;
10017
10019 NewFD->setDeletedAsWritten();
10020 break;
10021 }
10022
10023 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10024 D.isFunctionDefinition() && !isInline) {
10025 // Pre C++20 [class.mfct]p2:
10026 // A member function may be defined (8.4) in its class definition, in
10027 // which case it is an inline member function (7.1.2)
10028 // Post C++20 [class.mfct]p1:
10029 // If a member function is attached to the global module and is defined
10030 // in its class definition, it is inline.
10031 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10032 }
10033
10034 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10035 !CurContext->isRecord()) {
10036 // C++ [class.static]p1:
10037 // A data or function member of a class may be declared static
10038 // in a class definition, in which case it is a static member of
10039 // the class.
10040
10041 // Complain about the 'static' specifier if it's on an out-of-line
10042 // member function definition.
10043
10044 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10045 // member function template declaration and class member template
10046 // declaration (MSVC versions before 2015), warn about this.
10048 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10049 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10050 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10051 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10053 }
10054
10055 // C++11 [except.spec]p15:
10056 // A deallocation function with no exception-specification is treated
10057 // as if it were specified with noexcept(true).
10058 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10059 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10060 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10061 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10063 FPT->getReturnType(), FPT->getParamTypes(),
10065
10066 // C++20 [dcl.inline]/7
10067 // If an inline function or variable that is attached to a named module
10068 // is declared in a definition domain, it shall be defined in that
10069 // domain.
10070 // So, if the current declaration does not have a definition, we must
10071 // check at the end of the TU (or when the PMF starts) to see that we
10072 // have a definition at that point.
10073 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10074 NewFD->hasOwningModule() &&
10075 NewFD->getOwningModule()->isModulePurview()) {
10076 PendingInlineFuncDecls.insert(NewFD);
10077 }
10078 }
10079
10080 // Filter out previous declarations that don't match the scope.
10083 isMemberSpecialization ||
10084 isFunctionTemplateSpecialization);
10085
10086 // Handle GNU asm-label extension (encoded as an attribute).
10087 if (Expr *E = (Expr*) D.getAsmLabel()) {
10088 // The parser guarantees this is a string.
10090 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10091 /*IsLiteralLabel=*/true,
10092 SE->getStrTokenLoc(0)));
10093 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10094 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10096 if (I != ExtnameUndeclaredIdentifiers.end()) {
10097 if (isDeclExternC(NewFD)) {
10098 NewFD->addAttr(I->second);
10100 } else
10101 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10102 << /*Variable*/0 << NewFD;
10103 }
10104 }
10105
10106 // Copy the parameter declarations from the declarator D to the function
10107 // declaration NewFD, if they are available. First scavenge them into Params.
10109 unsigned FTIIdx;
10110 if (D.isFunctionDeclarator(FTIIdx)) {
10112
10113 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10114 // function that takes no arguments, not a function that takes a
10115 // single void argument.
10116 // We let through "const void" here because Sema::GetTypeForDeclarator
10117 // already checks for that case.
10118 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10119 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10120 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10121 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10122 Param->setDeclContext(NewFD);
10123 Params.push_back(Param);
10124
10125 if (Param->isInvalidDecl())
10126 NewFD->setInvalidDecl();
10127 }
10128 }
10129
10130 if (!getLangOpts().CPlusPlus) {
10131 // In C, find all the tag declarations from the prototype and move them
10132 // into the function DeclContext. Remove them from the surrounding tag
10133 // injection context of the function, which is typically but not always
10134 // the TU.
10135 DeclContext *PrototypeTagContext =
10137 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10138 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10139
10140 // We don't want to reparent enumerators. Look at their parent enum
10141 // instead.
10142 if (!TD) {
10143 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10144 TD = cast<EnumDecl>(ECD->getDeclContext());
10145 }
10146 if (!TD)
10147 continue;
10148 DeclContext *TagDC = TD->getLexicalDeclContext();
10149 if (!TagDC->containsDecl(TD))
10150 continue;
10151 TagDC->removeDecl(TD);
10152 TD->setDeclContext(NewFD);
10153 NewFD->addDecl(TD);
10154
10155 // Preserve the lexical DeclContext if it is not the surrounding tag
10156 // injection context of the FD. In this example, the semantic context of
10157 // E will be f and the lexical context will be S, while both the
10158 // semantic and lexical contexts of S will be f:
10159 // void f(struct S { enum E { a } f; } s);
10160 if (TagDC != PrototypeTagContext)
10161 TD->setLexicalDeclContext(TagDC);
10162 }
10163 }
10164 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10165 // When we're declaring a function with a typedef, typeof, etc as in the
10166 // following example, we'll need to synthesize (unnamed)
10167 // parameters for use in the declaration.
10168 //
10169 // @code
10170 // typedef void fn(int);
10171 // fn f;
10172 // @endcode
10173
10174 // Synthesize a parameter for each argument type.
10175 for (const auto &AI : FT->param_types()) {
10176 ParmVarDecl *Param =
10178 Param->setScopeInfo(0, Params.size());
10179 Params.push_back(Param);
10180 }
10181 } else {
10182 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10183 "Should not need args for typedef of non-prototype fn");
10184 }
10185
10186 // Finally, we know we have the right number of parameters, install them.
10187 NewFD->setParams(Params);
10188
10190 NewFD->addAttr(
10191 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10192
10193 // Functions returning a variably modified type violate C99 6.7.5.2p2
10194 // because all functions have linkage.
10195 if (!NewFD->isInvalidDecl() &&
10197 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10198 NewFD->setInvalidDecl();
10199 }
10200
10201 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10203 !NewFD->hasAttr<SectionAttr>())
10204 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10207
10208 // Apply an implicit SectionAttr if #pragma code_seg is active.
10209 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10210 !NewFD->hasAttr<SectionAttr>()) {
10211 NewFD->addAttr(SectionAttr::CreateImplicit(
10212 Context, CodeSegStack.CurrentValue->getString(),
10213 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10214 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10217 NewFD))
10218 NewFD->dropAttr<SectionAttr>();
10219 }
10220
10221 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10222 // active.
10224 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10225 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10227
10228 // Apply an implicit CodeSegAttr from class declspec or
10229 // apply an implicit SectionAttr from #pragma code_seg if active.
10230 if (!NewFD->hasAttr<CodeSegAttr>()) {
10232 D.isFunctionDefinition())) {
10233 NewFD->addAttr(SAttr);
10234 }
10235 }
10236
10237 // Handle attributes.
10238 ProcessDeclAttributes(S, NewFD, D);
10239 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10240 if (NewTVA && !NewTVA->isDefaultVersion() &&
10241 !Context.getTargetInfo().hasFeature("fmv")) {
10242 // Don't add to scope fmv functions declarations if fmv disabled
10243 AddToScope = false;
10244 return NewFD;
10245 }
10246
10247 if (getLangOpts().OpenCL) {
10248 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10249 // type declaration will generate a compilation error.
10250 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10251 if (AddressSpace != LangAS::Default) {
10252 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10253 NewFD->setInvalidDecl();
10254 }
10255 }
10256
10257 if (getLangOpts().HLSL) {
10259 // Skip operator overload which not identifier.
10260 // Also make sure NewFD is in translation-unit scope.
10261 if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
10262 NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
10263 S->getDepth() == 0) {
10264 CheckHLSLEntryPoint(NewFD);
10265 if (!NewFD->isInvalidDecl()) {
10266 auto Env = TargetInfo.getTriple().getEnvironment();
10267 HLSLShaderAttr::ShaderType ShaderType =
10268 static_cast<HLSLShaderAttr::ShaderType>(
10270 // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
10271 // function.
10272 if (HLSLShaderAttr *NT = NewFD->getAttr<HLSLShaderAttr>()) {
10273 if (NT->getType() != ShaderType)
10274 Diag(NT->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
10275 << NT;
10276 } else {
10277 NewFD->addAttr(HLSLShaderAttr::Create(Context, ShaderType,
10278 NewFD->getBeginLoc()));
10279 }
10280 }
10281 }
10282 // HLSL does not support specifying an address space on a function return
10283 // type.
10284 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10285 if (AddressSpace != LangAS::Default) {
10286 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10287 NewFD->setInvalidDecl();
10288 }
10289 }
10290
10291 if (!getLangOpts().CPlusPlus) {
10292 // Perform semantic checking on the function declaration.
10293 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10294 CheckMain(NewFD, D.getDeclSpec());
10295
10296 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10297 CheckMSVCRTEntryPoint(NewFD);
10298
10299 if (!NewFD->isInvalidDecl())
10301 isMemberSpecialization,
10303 else if (!Previous.empty())
10304 // Recover gracefully from an invalid redeclaration.
10305 D.setRedeclaration(true);
10306 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10307 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10308 "previous declaration set still overloaded");
10309
10310 // Diagnose no-prototype function declarations with calling conventions that
10311 // don't support variadic calls. Only do this in C and do it after merging
10312 // possibly prototyped redeclarations.
10313 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10314 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10315 CallingConv CC = FT->getExtInfo().getCC();
10316 if (!supportsVariadicCall(CC)) {
10317 // Windows system headers sometimes accidentally use stdcall without
10318 // (void) parameters, so we relax this to a warning.
10319 int DiagID =
10320 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10321 Diag(NewFD->getLocation(), DiagID)
10323 }
10324 }
10325
10331 } else {
10332 // C++11 [replacement.functions]p3:
10333 // The program's definitions shall not be specified as inline.
10334 //
10335 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10336 //
10337 // Suppress the diagnostic if the function is __attribute__((used)), since
10338 // that forces an external definition to be emitted.
10339 if (D.getDeclSpec().isInlineSpecified() &&
10341 !NewFD->hasAttr<UsedAttr>())
10343 diag::ext_operator_new_delete_declared_inline)
10344 << NewFD->getDeclName();
10345
10346 // If the declarator is a template-id, translate the parser's template
10347 // argument list into our AST format.
10349 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10350 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10351 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10352 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10353 TemplateId->NumArgs);
10354 translateTemplateArguments(TemplateArgsPtr,
10355 TemplateArgs);
10356
10357 HasExplicitTemplateArgs = true;
10358
10359 if (NewFD->isInvalidDecl()) {
10360 HasExplicitTemplateArgs = false;
10361 } else if (FunctionTemplate) {
10362 // Function template with explicit template arguments.
10363 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10364 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10365
10366 HasExplicitTemplateArgs = false;
10367 } else {
10368 assert((isFunctionTemplateSpecialization ||
10370 "should have a 'template<>' for this decl");
10371 // "friend void foo<>(int);" is an implicit specialization decl.
10372 isFunctionTemplateSpecialization = true;
10373 }
10374 } else if (isFriend && isFunctionTemplateSpecialization) {
10375 // This combination is only possible in a recovery case; the user
10376 // wrote something like:
10377 // template <> friend void foo(int);
10378 // which we're recovering from as if the user had written:
10379 // friend void foo<>(int);
10380 // Go ahead and fake up a template id.
10381 HasExplicitTemplateArgs = true;
10382 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10383 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10384 }
10385
10386 // We do not add HD attributes to specializations here because
10387 // they may have different constexpr-ness compared to their
10388 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10389 // may end up with different effective targets. Instead, a
10390 // specialization inherits its target attributes from its template
10391 // in the CheckFunctionTemplateSpecialization() call below.
10392 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10394
10395 // If it's a friend (and only if it's a friend), it's possible
10396 // that either the specialized function type or the specialized
10397 // template is dependent, and therefore matching will fail. In
10398 // this case, don't check the specialization yet.
10399 if (isFunctionTemplateSpecialization && isFriend &&
10400 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
10401 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
10402 TemplateArgs.arguments()))) {
10403 assert(HasExplicitTemplateArgs &&
10404 "friend function specialization without template args");
10405 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
10406 Previous))
10407 NewFD->setInvalidDecl();
10408 } else if (isFunctionTemplateSpecialization) {
10410 && !isFriend) {
10411 isDependentClassScopeExplicitSpecialization = true;
10412 } else if (!NewFD->isInvalidDecl() &&
10414 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
10415 Previous))
10416 NewFD->setInvalidDecl();
10417
10418 // C++ [dcl.stc]p1:
10419 // A storage-class-specifier shall not be specified in an explicit
10420 // specialization (14.7.3)
10423 if (Info && SC != SC_None) {
10424 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10425 Diag(NewFD->getLocation(),
10426 diag::err_explicit_specialization_inconsistent_storage_class)
10427 << SC
10430
10431 else
10432 Diag(NewFD->getLocation(),
10433 diag::ext_explicit_specialization_storage_class)
10436 }
10437 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10439 NewFD->setInvalidDecl();
10440 }
10441
10442 // Perform semantic checking on the function declaration.
10443 if (!isDependentClassScopeExplicitSpecialization) {
10444 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10445 CheckMain(NewFD, D.getDeclSpec());
10446
10447 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10448 CheckMSVCRTEntryPoint(NewFD);
10449
10450 if (!NewFD->isInvalidDecl())
10452 isMemberSpecialization,
10454 else if (!Previous.empty())
10455 // Recover gracefully from an invalid redeclaration.
10456 D.setRedeclaration(true);
10457 }
10458
10459 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10460 !D.isRedeclaration() ||
10461 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10462 "previous declaration set still overloaded");
10463
10464 NamedDecl *PrincipalDecl = (FunctionTemplate
10466 : NewFD);
10467
10468 if (isFriend && NewFD->getPreviousDecl()) {
10469 AccessSpecifier Access = AS_public;
10470 if (!NewFD->isInvalidDecl())
10471 Access = NewFD->getPreviousDecl()->getAccess();
10472
10473 NewFD->setAccess(Access);
10474 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10475 }
10476
10477 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10479 PrincipalDecl->setNonMemberOperator();
10480
10481 // If we have a function template, check the template parameter
10482 // list. This will check and merge default template arguments.
10483 if (FunctionTemplate) {
10484 FunctionTemplateDecl *PrevTemplate =
10486 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10487 PrevTemplate ? PrevTemplate->getTemplateParameters()
10488 : nullptr,
10493 : (D.getCXXScopeSpec().isSet() &&
10494 DC && DC->isRecord() &&
10495 DC->isDependentContext())
10498 }
10499
10500 if (NewFD->isInvalidDecl()) {
10501 // Ignore all the rest of this.
10502 } else if (!D.isRedeclaration()) {
10503 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10504 AddToScope };
10505 // Fake up an access specifier if it's supposed to be a class member.
10506 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10507 NewFD->setAccess(AS_public);
10508
10509 // Qualified decls generally require a previous declaration.
10510 if (D.getCXXScopeSpec().isSet()) {
10511 // ...with the major exception of templated-scope or
10512 // dependent-scope friend declarations.
10513
10514 // TODO: we currently also suppress this check in dependent
10515 // contexts because (1) the parameter depth will be off when
10516 // matching friend templates and (2) we might actually be
10517 // selecting a friend based on a dependent factor. But there
10518 // are situations where these conditions don't apply and we
10519 // can actually do this check immediately.
10520 //
10521 // Unless the scope is dependent, it's always an error if qualified
10522 // redeclaration lookup found nothing at all. Diagnose that now;
10523 // nothing will diagnose that error later.
10524 if (isFriend &&
10526 (!Previous.empty() && CurContext->isDependentContext()))) {
10527 // ignore these
10528 } else if (NewFD->isCPUDispatchMultiVersion() ||
10529 NewFD->isCPUSpecificMultiVersion()) {
10530 // ignore this, we allow the redeclaration behavior here to create new
10531 // versions of the function.
10532 } else {
10533 // The user tried to provide an out-of-line definition for a
10534 // function that is a member of a class or namespace, but there
10535 // was no such member function declared (C++ [class.mfct]p2,
10536 // C++ [namespace.memdef]p2). For example:
10537 //
10538 // class X {
10539 // void f() const;
10540 // };
10541 //
10542 // void X::f() { } // ill-formed
10543 //
10544 // Complain about this problem, and attempt to suggest close
10545 // matches (e.g., those that differ only in cv-qualifiers and
10546 // whether the parameter types are references).
10547
10549 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10550 AddToScope = ExtraArgs.AddToScope;
10551 return Result;
10552 }
10553 }
10554
10555 // Unqualified local friend declarations are required to resolve
10556 // to something.
10557 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10559 *this, Previous, NewFD, ExtraArgs, true, S)) {
10560 AddToScope = ExtraArgs.AddToScope;
10561 return Result;
10562 }
10563 }
10564 } else if (!D.isFunctionDefinition() &&
10565 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10566 !isFriend && !isFunctionTemplateSpecialization &&
10567 !isMemberSpecialization) {
10568 // An out-of-line member function declaration must also be a
10569 // definition (C++ [class.mfct]p2).
10570 // Note that this is not the case for explicit specializations of
10571 // function templates or member functions of class templates, per
10572 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10573 // extension for compatibility with old SWIG code which likes to
10574 // generate them.
10575 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10576 << D.getCXXScopeSpec().getRange();
10577 }
10578 }
10579
10580 // If this is the first declaration of a library builtin function, add
10581 // attributes as appropriate.
10582 if (!D.isRedeclaration()) {
10583 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10584 if (unsigned BuiltinID = II->getBuiltinID()) {
10585 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10586 if (!InStdNamespace &&
10588 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10589 // Validate the type matches unless this builtin is specified as
10590 // matching regardless of its declared type.
10591 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10592 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10593 } else {
10595 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10596 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10597
10598 if (!Error && !BuiltinType.isNull() &&
10600 NewFD->getType(), BuiltinType))
10601 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10602 }
10603 }
10604 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10605 isStdBuiltin(Context, NewFD, BuiltinID)) {
10606 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10607 }
10608 }
10609 }
10610 }
10611
10612 ProcessPragmaWeak(S, NewFD);
10613 checkAttributesAfterMerging(*this, *NewFD);
10614
10616
10617 if (NewFD->hasAttr<OverloadableAttr>() &&
10618 !NewFD->getType()->getAs<FunctionProtoType>()) {
10619 Diag(NewFD->getLocation(),
10620 diag::err_attribute_overloadable_no_prototype)
10621 << NewFD;
10622 NewFD->dropAttr<OverloadableAttr>();
10623 }
10624
10625 // If there's a #pragma GCC visibility in scope, and this isn't a class
10626 // member, set the visibility of this function.
10627 if (!DC->isRecord() && NewFD->isExternallyVisible())
10629
10630 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10631 // marking the function.
10632 AddCFAuditedAttribute(NewFD);
10633
10634 // If this is a function definition, check if we have to apply any
10635 // attributes (i.e. optnone and no_builtin) due to a pragma.
10636 if (D.isFunctionDefinition()) {
10637 AddRangeBasedOptnone(NewFD);
10639 AddSectionMSAllocText(NewFD);
10641 }
10642
10643 // If this is the first declaration of an extern C variable, update
10644 // the map of such variables.
10645 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10646 isIncompleteDeclExternC(*this, NewFD))
10648
10649 // Set this FunctionDecl's range up to the right paren.
10650 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10651
10652 if (D.isRedeclaration() && !Previous.empty()) {
10653 NamedDecl *Prev = Previous.getRepresentativeDecl();
10654 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10655 isMemberSpecialization ||
10656 isFunctionTemplateSpecialization,
10658 }
10659
10660 if (getLangOpts().CUDA) {
10661 IdentifierInfo *II = NewFD->getIdentifier();
10662 if (II && II->isStr(getCudaConfigureFuncName()) &&
10663 !NewFD->isInvalidDecl() &&
10666 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10669 }
10670
10671 // Variadic functions, other than a *declaration* of printf, are not allowed
10672 // in device-side CUDA code, unless someone passed
10673 // -fcuda-allow-variadic-functions.
10674 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10675 (NewFD->hasAttr<CUDADeviceAttr>() ||
10676 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10677 !(II && II->isStr("printf") && NewFD->isExternC() &&
10678 !D.isFunctionDefinition())) {
10679 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10680 }
10681 }
10682
10684
10685
10686
10687 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10688 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10689 if (SC == SC_Static) {
10690 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10691 D.setInvalidType();
10692 }
10693
10694 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10695 if (!NewFD->getReturnType()->isVoidType()) {
10696 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10697 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10698 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10699 : FixItHint());
10700 D.setInvalidType();
10701 }
10702
10704 for (auto *Param : NewFD->parameters())
10705 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10706
10707 if (getLangOpts().OpenCLCPlusPlus) {
10708 if (DC->isRecord()) {
10709 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10710 D.setInvalidType();
10711 }
10712 if (FunctionTemplate) {
10713 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10714 D.setInvalidType();
10715 }
10716 }
10717 }
10718
10719 if (getLangOpts().CPlusPlus) {
10720 // Precalculate whether this is a friend function template with a constraint
10721 // that depends on an enclosing template, per [temp.friend]p9.
10722 if (isFriend && FunctionTemplate &&
10725
10726 if (FunctionTemplate) {
10727 if (NewFD->isInvalidDecl())
10728 FunctionTemplate->setInvalidDecl();
10729 return FunctionTemplate;
10730 }
10731
10732 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10734 }
10735
10736 for (const ParmVarDecl *Param : NewFD->parameters()) {
10737 QualType PT = Param->getType();
10738
10739 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10740 // types.
10741 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10742 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10743 QualType ElemTy = PipeTy->getElementType();
10744 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10745 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10746 D.setInvalidType();
10747 }
10748 }
10749 }
10750 // WebAssembly tables can't be used as function parameters.
10751 if (Context.getTargetInfo().getTriple().isWasm()) {
10753 Diag(Param->getTypeSpecStartLoc(),
10754 diag::err_wasm_table_as_function_parameter);
10755 D.setInvalidType();
10756 }
10757 }
10758 }
10759
10760 // Here we have an function template explicit specialization at class scope.
10761 // The actual specialization will be postponed to template instatiation
10762 // time via the ClassScopeFunctionSpecializationDecl node.
10763 if (isDependentClassScopeExplicitSpecialization) {
10766 Context, CurContext, NewFD->getLocation(),
10767 cast<CXXMethodDecl>(NewFD),
10768 HasExplicitTemplateArgs, TemplateArgs);
10769 CurContext->addDecl(NewSpec);
10770 AddToScope = false;
10771 }
10772
10773 // Diagnose availability attributes. Availability cannot be used on functions
10774 // that are run during load/unload.
10775 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10776 if (NewFD->hasAttr<ConstructorAttr>()) {
10777 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10778 << 1;
10779 NewFD->dropAttr<AvailabilityAttr>();
10780 }
10781 if (NewFD->hasAttr<DestructorAttr>()) {
10782 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10783 << 2;
10784 NewFD->dropAttr<AvailabilityAttr>();
10785 }
10786 }
10787
10788 // Diagnose no_builtin attribute on function declaration that are not a
10789 // definition.
10790 // FIXME: We should really be doing this in
10791 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10792 // the FunctionDecl and at this point of the code
10793 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10794 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10795 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10796 switch (D.getFunctionDefinitionKind()) {
10799 Diag(NBA->getLocation(),
10800 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10801 << NBA->getSpelling();
10802 break;
10804 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10805 << NBA->getSpelling();
10806 break;
10808 break;
10809 }
10810
10811 return NewFD;
10812}
10813
10814/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10815/// when __declspec(code_seg) "is applied to a class, all member functions of
10816/// the class and nested classes -- this includes compiler-generated special
10817/// member functions -- are put in the specified segment."
10818/// The actual behavior is a little more complicated. The Microsoft compiler
10819/// won't check outer classes if there is an active value from #pragma code_seg.
10820/// The CodeSeg is always applied from the direct parent but only from outer
10821/// classes when the #pragma code_seg stack is empty. See:
10822/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10823/// available since MS has removed the page.
10825 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10826 if (!Method)
10827 return nullptr;
10828 const CXXRecordDecl *Parent = Method->getParent();
10829 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10830 Attr *NewAttr = SAttr->clone(S.getASTContext());
10831 NewAttr->setImplicit(true);
10832 return NewAttr;
10833 }
10834
10835 // The Microsoft compiler won't check outer classes for the CodeSeg
10836 // when the #pragma code_seg stack is active.
10837 if (S.CodeSegStack.CurrentValue)
10838 return nullptr;
10839
10840 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10841 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10842 Attr *NewAttr = SAttr->clone(S.getASTContext());
10843 NewAttr->setImplicit(true);
10844 return NewAttr;
10845 }
10846 }
10847 return nullptr;
10848}
10849
10850/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10851/// containing class. Otherwise it will return implicit SectionAttr if the
10852/// function is a definition and there is an active value on CodeSegStack
10853/// (from the current #pragma code-seg value).
10854///
10855/// \param FD Function being declared.
10856/// \param IsDefinition Whether it is a definition or just a declaration.
10857/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10858/// nullptr if no attribute should be added.
10860 bool IsDefinition) {
10861 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10862 return A;
10863 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10864 CodeSegStack.CurrentValue)
10865 return SectionAttr::CreateImplicit(
10866 getASTContext(), CodeSegStack.CurrentValue->getString(),
10867 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10868 return nullptr;
10869}
10870
10871/// Determines if we can perform a correct type check for \p D as a
10872/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10873/// best-effort check.
10874///
10875/// \param NewD The new declaration.
10876/// \param OldD The old declaration.
10877/// \param NewT The portion of the type of the new declaration to check.
10878/// \param OldT The portion of the type of the old declaration to check.
10880 QualType NewT, QualType OldT) {
10882 return true;
10883
10884 // For dependently-typed local extern declarations and friends, we can't
10885 // perform a correct type check in general until instantiation:
10886 //
10887 // int f();
10888 // template<typename T> void g() { T f(); }
10889 //
10890 // (valid if g() is only instantiated with T = int).
10891 if (NewT->isDependentType() &&
10892 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10893 return false;
10894
10895 // Similarly, if the previous declaration was a dependent local extern
10896 // declaration, we don't really know its type yet.
10897 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10898 return false;
10899
10900 return true;
10901}
10902
10903/// Checks if the new declaration declared in dependent context must be
10904/// put in the same redeclaration chain as the specified declaration.
10905///
10906/// \param D Declaration that is checked.
10907/// \param PrevDecl Previous declaration found with proper lookup method for the
10908/// same declaration name.
10909/// \returns True if D must be added to the redeclaration chain which PrevDecl
10910/// belongs to.
10911///
10914 return true;
10915
10916 // Don't chain dependent friend function definitions until instantiation, to
10917 // permit cases like
10918 //
10919 // void func();
10920 // template<typename T> class C1 { friend void func() {} };
10921 // template<typename T> class C2 { friend void func() {} };
10922 //
10923 // ... which is valid if only one of C1 and C2 is ever instantiated.
10924 //
10925 // FIXME: This need only apply to function definitions. For now, we proxy
10926 // this by checking for a file-scope function. We do not want this to apply
10927 // to friend declarations nominating member functions, because that gets in
10928 // the way of access checks.
10930 return false;
10931
10932 auto *VD = dyn_cast<ValueDecl>(D);
10933 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10934 return !VD || !PrevVD ||
10935 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10936 PrevVD->getType());
10937}
10938
10939/// Check the target or target_version attribute of the function for
10940/// MultiVersion validity.
10941///
10942/// Returns true if there was an error, false otherwise.
10943static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10944 const auto *TA = FD->getAttr<TargetAttr>();
10945 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10946 assert(
10947 (TA || TVA) &&
10948 "MultiVersion candidate requires a target or target_version attribute");
10950 enum ErrType { Feature = 0, Architecture = 1 };
10951
10952 if (TA) {
10953 ParsedTargetAttr ParseInfo =
10954 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10955 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10956 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10957 << Architecture << ParseInfo.CPU;
10958 return true;
10959 }
10960 for (const auto &Feat : ParseInfo.Features) {
10961 auto BareFeat = StringRef{Feat}.substr(1);
10962 if (Feat[0] == '-') {
10963 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10964 << Feature << ("no-" + BareFeat).str();
10965 return true;
10966 }
10967
10968 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10969 !TargetInfo.isValidFeatureName(BareFeat)) {
10970 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10971 << Feature << BareFeat;
10972 return true;
10973 }
10974 }
10975 }
10976
10977 if (TVA) {
10979 TVA->getFeatures(Feats);
10980 for (const auto &Feat : Feats) {
10981 if (!TargetInfo.validateCpuSupports(Feat)) {
10982 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10983 << Feature << Feat;
10984 return true;
10985 }
10986 }
10987 }
10988 return false;
10989}
10990
10991// Provide a white-list of attributes that are allowed to be combined with
10992// multiversion functions.
10994 MultiVersionKind MVKind) {
10995 // Note: this list/diagnosis must match the list in
10996 // checkMultiversionAttributesAllSame.
10997 switch (Kind) {
10998 default:
10999 return false;
11000 case attr::Used:
11001 return MVKind == MultiVersionKind::Target;
11002 case attr::NonNull:
11003 case attr::NoThrow:
11004 return true;
11005 }
11006}
11007
11009 const FunctionDecl *FD,
11010 const FunctionDecl *CausedFD,
11011 MultiVersionKind MVKind) {
11012 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11013 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11014 << static_cast<unsigned>(MVKind) << A;
11015 if (CausedFD)
11016 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11017 return true;
11018 };
11019
11020 for (const Attr *A : FD->attrs()) {
11021 switch (A->getKind()) {
11022 case attr::CPUDispatch:
11023 case attr::CPUSpecific:
11024 if (MVKind != MultiVersionKind::CPUDispatch &&
11026 return Diagnose(S, A);
11027 break;
11028 case attr::Target:
11029 if (MVKind != MultiVersionKind::Target)
11030 return Diagnose(S, A);
11031 break;
11032 case attr::TargetVersion:
11033 if (MVKind != MultiVersionKind::TargetVersion)
11034 return Diagnose(S, A);
11035 break;
11036 case attr::TargetClones:
11037 if (MVKind != MultiVersionKind::TargetClones)
11038 return Diagnose(S, A);
11039 break;
11040 default:
11041 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11042 return Diagnose(S, A);
11043 break;
11044 }
11045 }
11046 return false;
11047}
11048
11050 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11051 const PartialDiagnostic &NoProtoDiagID,
11052 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11053 const PartialDiagnosticAt &NoSupportDiagIDAt,
11054 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11055 bool ConstexprSupported, bool CLinkageMayDiffer) {
11056 enum DoesntSupport {
11057 FuncTemplates = 0,
11058 VirtFuncs = 1,
11059 DeducedReturn = 2,
11060 Constructors = 3,
11061 Destructors = 4,
11062 DeletedFuncs = 5,
11063 DefaultedFuncs = 6,
11064 ConstexprFuncs = 7,
11065 ConstevalFuncs = 8,
11066 Lambda = 9,
11067 };
11068 enum Different {
11069 CallingConv = 0,
11070 ReturnType = 1,
11071 ConstexprSpec = 2,
11072 InlineSpec = 3,
11073 Linkage = 4,
11074 LanguageLinkage = 5,
11075 };
11076
11077 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11078 !OldFD->getType()->getAs<FunctionProtoType>()) {
11079 Diag(OldFD->getLocation(), NoProtoDiagID);
11080 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11081 return true;
11082 }
11083
11084 if (NoProtoDiagID.getDiagID() != 0 &&
11085 !NewFD->getType()->getAs<FunctionProtoType>())
11086 return Diag(NewFD->getLocation(), NoProtoDiagID);
11087
11088 if (!TemplatesSupported &&
11090 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11091 << FuncTemplates;
11092
11093 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11094 if (NewCXXFD->isVirtual())
11095 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11096 << VirtFuncs;
11097
11098 if (isa<CXXConstructorDecl>(NewCXXFD))
11099 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11100 << Constructors;
11101
11102 if (isa<CXXDestructorDecl>(NewCXXFD))
11103 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11104 << Destructors;
11105 }
11106
11107 if (NewFD->isDeleted())
11108 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11109 << DeletedFuncs;
11110
11111 if (NewFD->isDefaulted())
11112 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11113 << DefaultedFuncs;
11114
11115 if (!ConstexprSupported && NewFD->isConstexpr())
11116 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11117 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11118
11119 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11120 const auto *NewType = cast<FunctionType>(NewQType);
11121 QualType NewReturnType = NewType->getReturnType();
11122
11123 if (NewReturnType->isUndeducedType())
11124 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11125 << DeducedReturn;
11126
11127 // Ensure the return type is identical.
11128 if (OldFD) {
11129 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11130 const auto *OldType = cast<FunctionType>(OldQType);
11131 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11132 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11133
11134 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11135 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11136
11137 QualType OldReturnType = OldType->getReturnType();
11138
11139 if (OldReturnType != NewReturnType)
11140 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11141
11142 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11143 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11144
11145 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11146 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11147
11148 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11149 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11150
11151 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11152 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11153
11155 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11156 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11157 return true;
11158 }
11159 return false;
11160}
11161
11163 const FunctionDecl *NewFD,
11164 bool CausesMV,
11165 MultiVersionKind MVKind) {
11167 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11168 if (OldFD)
11169 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11170 return true;
11171 }
11172
11173 bool IsCPUSpecificCPUDispatchMVKind =
11176
11177 if (CausesMV && OldFD &&
11178 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11179 return true;
11180
11181 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11182 return true;
11183
11184 // Only allow transition to MultiVersion if it hasn't been used.
11185 if (OldFD && CausesMV && OldFD->isUsed(false))
11186 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11187
11189 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11191 S.PDiag(diag::note_multiversioning_caused_here)),
11193 S.PDiag(diag::err_multiversion_doesnt_support)
11194 << static_cast<unsigned>(MVKind)),
11196 S.PDiag(diag::err_multiversion_diff)),
11197 /*TemplatesSupported=*/false,
11198 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11199 /*CLinkageMayDiffer=*/false);
11200}
11201
11202/// Check the validity of a multiversion function declaration that is the
11203/// first of its kind. Also sets the multiversion'ness' of the function itself.
11204///
11205/// This sets NewFD->isInvalidDecl() to true if there was an error.
11206///
11207/// Returns true if there was an error, false otherwise.
11210 assert(MVKind != MultiVersionKind::None &&
11211 "Function lacks multiversion attribute");
11212 const auto *TA = FD->getAttr<TargetAttr>();
11213 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11214 // Target and target_version only causes MV if it is default, otherwise this
11215 // is a normal function.
11216 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11217 return false;
11218
11219 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11220 FD->setInvalidDecl();
11221 return true;
11222 }
11223
11224 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11225 FD->setInvalidDecl();
11226 return true;
11227 }
11228
11229 FD->setIsMultiVersion();
11230 return false;
11231}
11232
11234 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11236 return true;
11237 }
11238
11239 return false;
11240}
11241
11243 FunctionDecl *NewFD,
11244 bool &Redeclaration,
11245 NamedDecl *&OldDecl,
11247 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11248 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11249 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11250 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11251 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11252 // to change, this is a simple redeclaration.
11253 if ((NewTA && !NewTA->isDefaultVersion() &&
11254 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11255 (NewTVA && !NewTVA->isDefaultVersion() &&
11256 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11257 return false;
11258
11259 // Otherwise, this decl causes MultiVersioning.
11260 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11263 NewFD->setInvalidDecl();
11264 return true;
11265 }
11266
11267 if (CheckMultiVersionValue(S, NewFD)) {
11268 NewFD->setInvalidDecl();
11269 return true;
11270 }
11271
11272 // If this is 'default', permit the forward declaration.
11273 if (!OldFD->isMultiVersion() &&
11274 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11275 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11276 Redeclaration = true;
11277 OldDecl = OldFD;
11278 OldFD->setIsMultiVersion();
11279 NewFD->setIsMultiVersion();
11280 return false;
11281 }
11282
11283 if (CheckMultiVersionValue(S, OldFD)) {
11284 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11285 NewFD->setInvalidDecl();
11286 return true;
11287 }
11288
11289 if (NewTA) {
11290 ParsedTargetAttr OldParsed =
11292 OldTA->getFeaturesStr());
11293 llvm::sort(OldParsed.Features);
11294 ParsedTargetAttr NewParsed =
11296 NewTA->getFeaturesStr());
11297 // Sort order doesn't matter, it just needs to be consistent.
11298 llvm::sort(NewParsed.Features);
11299 if (OldParsed == NewParsed) {
11300 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11301 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11302 NewFD->setInvalidDecl();
11303 return true;
11304 }
11305 }
11306
11307 if (NewTVA) {
11309 OldTVA->getFeatures(Feats);
11310 llvm::sort(Feats);
11312 NewTVA->getFeatures(NewFeats);
11313 llvm::sort(NewFeats);
11314
11315 if (Feats == NewFeats) {
11316 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11317 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11318 NewFD->setInvalidDecl();
11319 return true;
11320 }
11321 }
11322
11323 for (const auto *FD : OldFD->redecls()) {
11324 const auto *CurTA = FD->getAttr<TargetAttr>();
11325 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11326 // We allow forward declarations before ANY multiversioning attributes, but
11327 // nothing after the fact.
11329 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11330 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11331 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11332 << (NewTA ? 0 : 2);
11333 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11334 NewFD->setInvalidDecl();
11335 return true;
11336 }
11337 }
11338
11339 OldFD->setIsMultiVersion();
11340 NewFD->setIsMultiVersion();
11341 Redeclaration = false;
11342 OldDecl = nullptr;
11343 Previous.clear();
11344 return false;
11345}
11346
11348 MultiVersionKind New) {
11349 if (Old == New || Old == MultiVersionKind::None ||
11351 return true;
11352
11353 return (Old == MultiVersionKind::CPUDispatch &&
11357}
11358
11359/// Check the validity of a new function declaration being added to an existing
11360/// multiversioned declaration collection.
11362 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11363 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11364 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11365 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11366 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11367 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11368 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11369 // Disallow mixing of multiversioning types.
11370 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11371 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11372 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11373 NewFD->setInvalidDecl();
11374 return true;
11375 }
11376
11377 ParsedTargetAttr NewParsed;
11378 if (NewTA) {
11380 NewTA->getFeaturesStr());
11381 llvm::sort(NewParsed.Features);
11382 }
11384 if (NewTVA) {
11385 NewTVA->getFeatures(NewFeats);
11386 llvm::sort(NewFeats);
11387 }
11388
11389 bool UseMemberUsingDeclRules =
11390 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11391
11392 bool MayNeedOverloadableChecks =
11394
11395 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11396 // of a previous member of the MultiVersion set.
11397 for (NamedDecl *ND : Previous) {
11398 FunctionDecl *CurFD = ND->getAsFunction();
11399 if (!CurFD || CurFD->isInvalidDecl())
11400 continue;
11401 if (MayNeedOverloadableChecks &&
11402 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11403 continue;
11404
11405 if (NewMVKind == MultiVersionKind::None &&
11406 OldMVKind == MultiVersionKind::TargetVersion) {
11407 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11408 S.Context, "default", NewFD->getSourceRange()));
11409 NewFD->setIsMultiVersion();
11411 if (!NewTVA) {
11412 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11413 NewTVA->getFeatures(NewFeats);
11414 llvm::sort(NewFeats);
11415 }
11416 }
11417
11418 switch (NewMVKind) {
11420 assert(OldMVKind == MultiVersionKind::TargetClones &&
11421 "Only target_clones can be omitted in subsequent declarations");
11422 break;
11424 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11425 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11426 NewFD->setIsMultiVersion();
11427 Redeclaration = true;
11428 OldDecl = ND;
11429 return false;
11430 }
11431
11432 ParsedTargetAttr CurParsed =
11434 CurTA->getFeaturesStr());
11435 llvm::sort(CurParsed.Features);
11436 if (CurParsed == NewParsed) {
11437 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11438 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11439 NewFD->setInvalidDecl();
11440 return true;
11441 }
11442 break;
11443 }
11445 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11446 if (CurTVA->getName() == NewTVA->getName()) {
11447 NewFD->setIsMultiVersion();
11448 Redeclaration = true;
11449 OldDecl = ND;
11450 return false;
11451 }
11453 if (CurTVA) {
11454 CurTVA->getFeatures(CurFeats);
11455 llvm::sort(CurFeats);
11456 }
11457 if (CurFeats == NewFeats) {
11458 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11459 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11460 NewFD->setInvalidDecl();
11461 return true;
11462 }
11463 break;
11464 }
11466 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11467 Redeclaration = true;
11468 OldDecl = CurFD;
11469 NewFD->setIsMultiVersion();
11470
11471 if (CurClones && NewClones &&
11472 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11473 !std::equal(CurClones->featuresStrs_begin(),
11474 CurClones->featuresStrs_end(),
11475 NewClones->featuresStrs_begin()))) {
11476 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11477 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11478 NewFD->setInvalidDecl();
11479 return true;
11480 }
11481
11482 return false;
11483 }
11486 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11487 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11488 // Handle CPUDispatch/CPUSpecific versions.
11489 // Only 1 CPUDispatch function is allowed, this will make it go through
11490 // the redeclaration errors.
11491 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11492 CurFD->hasAttr<CPUDispatchAttr>()) {
11493 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11494 std::equal(
11495 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11496 NewCPUDisp->cpus_begin(),
11497 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11498 return Cur->getName() == New->getName();
11499 })) {
11500 NewFD->setIsMultiVersion();
11501 Redeclaration = true;
11502 OldDecl = ND;
11503 return false;
11504 }
11505
11506 // If the declarations don't match, this is an error condition.
11507 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11508 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11509 NewFD->setInvalidDecl();
11510 return true;
11511 }
11512 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11513 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11514 std::equal(
11515 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11516 NewCPUSpec->cpus_begin(),
11517 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11518 return Cur->getName() == New->getName();
11519 })) {
11520 NewFD->setIsMultiVersion();
11521 Redeclaration = true;
11522 OldDecl = ND;
11523 return false;
11524 }
11525
11526 // Only 1 version of CPUSpecific is allowed for each CPU.
11527 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11528 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11529 if (CurII == NewII) {
11530 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11531 << NewII;
11532 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11533 NewFD->setInvalidDecl();
11534 return true;
11535 }
11536 }
11537 }
11538 }
11539 break;
11540 }
11541 }
11542 }
11543
11544 // Else, this is simply a non-redecl case. Checking the 'value' is only
11545 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11546 // handled in the attribute adding step.
11547 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11548 NewMVKind == MultiVersionKind::Target) &&
11549 CheckMultiVersionValue(S, NewFD)) {
11550 NewFD->setInvalidDecl();
11551 return true;
11552 }
11553
11554 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11555 !OldFD->isMultiVersion(), NewMVKind)) {
11556 NewFD->setInvalidDecl();
11557 return true;
11558 }
11559
11560 // Permit forward declarations in the case where these two are compatible.
11561 if (!OldFD->isMultiVersion()) {
11562 OldFD->setIsMultiVersion();
11563 NewFD->setIsMultiVersion();
11564 Redeclaration = true;
11565 OldDecl = OldFD;
11566 return false;
11567 }
11568
11569 NewFD->setIsMultiVersion();
11570 Redeclaration = false;
11571 OldDecl = nullptr;
11572 Previous.clear();
11573 return false;
11574}
11575
11576/// Check the validity of a mulitversion function declaration.
11577/// Also sets the multiversion'ness' of the function itself.
11578///
11579/// This sets NewFD->isInvalidDecl() to true if there was an error.
11580///
11581/// Returns true if there was an error, false otherwise.
11583 bool &Redeclaration, NamedDecl *&OldDecl,
11585 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11586 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11587 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11588 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11589 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11590 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11591
11592 // Main isn't allowed to become a multiversion function, however it IS
11593 // permitted to have 'main' be marked with the 'target' optimization hint,
11594 // for 'target_version' only default is allowed.
11595 if (NewFD->isMain()) {
11596 if (MVKind != MultiVersionKind::None &&
11597 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11598 !(MVKind == MultiVersionKind::TargetVersion &&
11599 NewTVA->isDefaultVersion())) {
11600 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11601 NewFD->setInvalidDecl();
11602 return true;
11603 }
11604 return false;
11605 }
11606
11607 // Target attribute on AArch64 is not used for multiversioning
11608 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11609 return false;
11610
11611 if (!OldDecl || !OldDecl->getAsFunction() ||
11612 OldDecl->getDeclContext()->getRedeclContext() !=
11613 NewFD->getDeclContext()->getRedeclContext()) {
11614 // If there's no previous declaration, AND this isn't attempting to cause
11615 // multiversioning, this isn't an error condition.
11616 if (MVKind == MultiVersionKind::None)
11617 return false;
11618 return CheckMultiVersionFirstFunction(S, NewFD);
11619 }
11620
11621 FunctionDecl *OldFD = OldDecl->getAsFunction();
11622
11623 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11624 // No target_version attributes mean default
11625 if (!NewTVA) {
11626 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11627 if (OldTVA) {
11628 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11629 S.Context, "default", NewFD->getSourceRange()));
11630 NewFD->setIsMultiVersion();
11631 OldFD->setIsMultiVersion();
11632 OldDecl = OldFD;
11633 Redeclaration = true;
11634 return true;
11635 }
11636 }
11637 return false;
11638 }
11639
11640 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11641 // for target_clones and target_version.
11642 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11645 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11647 NewFD->setInvalidDecl();
11648 return true;
11649 }
11650
11651 if (!OldFD->isMultiVersion()) {
11652 switch (MVKind) {
11655 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11656 OldDecl, Previous);
11658 if (OldFD->isUsed(false)) {
11659 NewFD->setInvalidDecl();
11660 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11661 }
11662 OldFD->setIsMultiVersion();
11663 break;
11664
11668 break;
11669 }
11670 }
11671
11672 // At this point, we have a multiversion function decl (in OldFD) AND an
11673 // appropriate attribute in the current function decl. Resolve that these are
11674 // still compatible with previous declarations.
11675 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11676 NewCPUSpec, NewClones, Redeclaration,
11677 OldDecl, Previous);
11678}
11679
11680/// Perform semantic checking of a new function declaration.
11681///
11682/// Performs semantic analysis of the new function declaration
11683/// NewFD. This routine performs all semantic checking that does not
11684/// require the actual declarator involved in the declaration, and is
11685/// used both for the declaration of functions as they are parsed
11686/// (called via ActOnDeclarator) and for the declaration of functions
11687/// that have been instantiated via C++ template instantiation (called
11688/// via InstantiateDecl).
11689///
11690/// \param IsMemberSpecialization whether this new function declaration is
11691/// a member specialization (that replaces any definition provided by the
11692/// previous declaration).
11693///
11694/// This sets NewFD->isInvalidDecl() to true if there was an error.
11695///
11696/// \returns true if the function declaration is a redeclaration.
11699 bool IsMemberSpecialization,
11700 bool DeclIsDefn) {
11701 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11702 "Variably modified return types are not handled here");
11703
11704 // Determine whether the type of this function should be merged with
11705 // a previous visible declaration. This never happens for functions in C++,
11706 // and always happens in C if the previous declaration was visible.
11707 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11708 !Previous.isShadowed();
11709
11710 bool Redeclaration = false;
11711 NamedDecl *OldDecl = nullptr;
11712 bool MayNeedOverloadableChecks = false;
11713
11714 // Merge or overload the declaration with an existing declaration of
11715 // the same name, if appropriate.
11716 if (!Previous.empty()) {
11717 // Determine whether NewFD is an overload of PrevDecl or
11718 // a declaration that requires merging. If it's an overload,
11719 // there's no more work to do here; we'll just add the new
11720 // function to the scope.
11722 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11723 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11724 Redeclaration = true;
11725 OldDecl = Candidate;
11726 }
11727 } else {
11728 MayNeedOverloadableChecks = true;
11729 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11730 /*NewIsUsingDecl*/ false)) {
11731 case Ovl_Match:
11732 Redeclaration = true;
11733 break;
11734
11735 case Ovl_NonFunction:
11736 Redeclaration = true;
11737 break;
11738
11739 case Ovl_Overload:
11740 Redeclaration = false;
11741 break;
11742 }
11743 }
11744 }
11745
11746 // Check for a previous extern "C" declaration with this name.
11747 if (!Redeclaration &&
11749 if (!Previous.empty()) {
11750 // This is an extern "C" declaration with the same name as a previous
11751 // declaration, and thus redeclares that entity...
11752 Redeclaration = true;
11753 OldDecl = Previous.getFoundDecl();
11754 MergeTypeWithPrevious = false;
11755
11756 // ... except in the presence of __attribute__((overloadable)).
11757 if (OldDecl->hasAttr<OverloadableAttr>() ||
11758 NewFD->hasAttr<OverloadableAttr>()) {
11759 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11760 MayNeedOverloadableChecks = true;
11761 Redeclaration = false;
11762 OldDecl = nullptr;
11763 }
11764 }
11765 }
11766 }
11767
11768 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11769 return Redeclaration;
11770
11771 // PPC MMA non-pointer types are not allowed as function return types.
11772 if (Context.getTargetInfo().getTriple().isPPC64() &&
11773 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11774 NewFD->setInvalidDecl();
11775 }
11776
11777 // C++11 [dcl.constexpr]p8:
11778 // A constexpr specifier for a non-static member function that is not
11779 // a constructor declares that member function to be const.
11780 //
11781 // This needs to be delayed until we know whether this is an out-of-line
11782 // definition of a static member function.
11783 //
11784 // This rule is not present in C++1y, so we produce a backwards
11785 // compatibility warning whenever it happens in C++11.
11786 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11787 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11788 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11789 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11790 CXXMethodDecl *OldMD = nullptr;
11791 if (OldDecl)
11792 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11793 if (!OldMD || !OldMD->isStatic()) {
11794 const FunctionProtoType *FPT =
11797 EPI.TypeQuals.addConst();
11799 FPT->getParamTypes(), EPI));
11800
11801 // Warn that we did this, if we're not performing template instantiation.
11802 // In that case, we'll have warned already when the template was defined.
11803 if (!inTemplateInstantiation()) {
11804 SourceLocation AddConstLoc;
11807 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11808
11809 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11810 << FixItHint::CreateInsertion(AddConstLoc, " const");
11811 }
11812 }
11813 }
11814
11815 if (Redeclaration) {
11816 // NewFD and OldDecl represent declarations that need to be
11817 // merged.
11818 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11819 DeclIsDefn)) {
11820 NewFD->setInvalidDecl();
11821 return Redeclaration;
11822 }
11823
11824 Previous.clear();
11825 Previous.addDecl(OldDecl);
11826
11827 if (FunctionTemplateDecl *OldTemplateDecl =
11828 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11829 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11830 FunctionTemplateDecl *NewTemplateDecl
11832 assert(NewTemplateDecl && "Template/non-template mismatch");
11833
11834 // The call to MergeFunctionDecl above may have created some state in
11835 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11836 // can add it as a redeclaration.
11837 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11838
11839 NewFD->setPreviousDeclaration(OldFD);
11840 if (NewFD->isCXXClassMember()) {
11841 NewFD->setAccess(OldTemplateDecl->getAccess());
11842 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11843 }
11844
11845 // If this is an explicit specialization of a member that is a function
11846 // template, mark it as a member specialization.
11847 if (IsMemberSpecialization &&
11848 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11849 NewTemplateDecl->setMemberSpecialization();
11850 assert(OldTemplateDecl->isMemberSpecialization());
11851 // Explicit specializations of a member template do not inherit deleted
11852 // status from the parent member template that they are specializing.
11853 if (OldFD->isDeleted()) {
11854 // FIXME: This assert will not hold in the presence of modules.
11855 assert(OldFD->getCanonicalDecl() == OldFD);
11856 // FIXME: We need an update record for this AST mutation.
11857 OldFD->setDeletedAsWritten(false);
11858 }
11859 }
11860
11861 } else {
11862 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11863 auto *OldFD = cast<FunctionDecl>(OldDecl);
11864 // This needs to happen first so that 'inline' propagates.
11865 NewFD->setPreviousDeclaration(OldFD);
11866 if (NewFD->isCXXClassMember())
11867 NewFD->setAccess(OldFD->getAccess());
11868 }
11869 }
11870 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11871 !NewFD->getAttr<OverloadableAttr>()) {
11872 assert((Previous.empty() ||
11873 llvm::any_of(Previous,
11874 [](const NamedDecl *ND) {
11875 return ND->hasAttr<OverloadableAttr>();
11876 })) &&
11877 "Non-redecls shouldn't happen without overloadable present");
11878
11879 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11880 const auto *FD = dyn_cast<FunctionDecl>(ND);
11881 return FD && !FD->hasAttr<OverloadableAttr>();
11882 });
11883
11884 if (OtherUnmarkedIter != Previous.end()) {
11885 Diag(NewFD->getLocation(),
11886 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11887 Diag((*OtherUnmarkedIter)->getLocation(),
11888 diag::note_attribute_overloadable_prev_overload)
11889 << false;
11890
11891 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11892 }
11893 }
11894
11895 if (LangOpts.OpenMP)
11897
11898 // Semantic checking for this function declaration (in isolation).
11899
11900 if (getLangOpts().CPlusPlus) {
11901 // C++-specific checks.
11902 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11903 CheckConstructor(Constructor);
11904 } else if (CXXDestructorDecl *Destructor =
11905 dyn_cast<CXXDestructorDecl>(NewFD)) {
11906 // We check here for invalid destructor names.
11907 // If we have a friend destructor declaration that is dependent, we can't
11908 // diagnose right away because cases like this are still valid:
11909 // template <class T> struct A { friend T::X::~Y(); };
11910 // struct B { struct Y { ~Y(); }; using X = Y; };
11911 // template struct A<B>;
11913 !Destructor->getThisType()->isDependentType()) {
11914 CXXRecordDecl *Record = Destructor->getParent();
11915 QualType ClassType = Context.getTypeDeclType(Record);
11916
11918 Context.getCanonicalType(ClassType));
11919 if (NewFD->getDeclName() != Name) {
11920 Diag(NewFD->getLocation(), diag::err_destructor_name);
11921 NewFD->setInvalidDecl();
11922 return Redeclaration;
11923 }
11924 }
11925 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11926 if (auto *TD = Guide->getDescribedFunctionTemplate())
11928
11929 // A deduction guide is not on the list of entities that can be
11930 // explicitly specialized.
11931 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11932 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11933 << /*explicit specialization*/ 1;
11934 }
11935
11936 // Find any virtual functions that this function overrides.
11937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11938 if (!Method->isFunctionTemplateSpecialization() &&
11939 !Method->getDescribedFunctionTemplate() &&
11940 Method->isCanonicalDecl()) {
11941 AddOverriddenMethods(Method->getParent(), Method);
11942 }
11943 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11944 // C++2a [class.virtual]p6
11945 // A virtual method shall not have a requires-clause.
11947 diag::err_constrained_virtual_method);
11948
11949 if (Method->isStatic())
11951 }
11952
11953 // C++20: dcl.decl.general p4:
11954 // The optional requires-clause ([temp.pre]) in an init-declarator or
11955 // member-declarator shall be present only if the declarator declares a
11956 // templated function ([dcl.fct]).
11957 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
11958 // [temp.pre]/8:
11959 // An entity is templated if it is
11960 // - a template,
11961 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
11962 // templated entity,
11963 // - a member of a templated entity,
11964 // - an enumerator for an enumeration that is a templated entity, or
11965 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
11966 // appearing in the declaration of a templated entity. [Note 6: A local
11967 // class, a local or block variable, or a friend function defined in a
11968 // templated entity is a templated entity. — end note]
11969 //
11970 // A templated function is a function template or a function that is
11971 // templated. A templated class is a class template or a class that is
11972 // templated. A templated variable is a variable template or a variable
11973 // that is templated.
11974
11975 if (!NewFD->getDescribedFunctionTemplate() && // -a template
11976 // defined... in a templated entity
11977 !(DeclIsDefn && NewFD->isTemplated()) &&
11978 // a member of a templated entity
11979 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
11980 // Don't complain about instantiations, they've already had these
11981 // rules + others enforced.
11982 !NewFD->isTemplateInstantiation()) {
11983 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
11984 }
11985 }
11986
11987 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11988 ActOnConversionDeclarator(Conversion);
11989
11990 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11991 if (NewFD->isOverloadedOperator() &&
11993 NewFD->setInvalidDecl();
11994 return Redeclaration;
11995 }
11996
11997 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11998 if (NewFD->getLiteralIdentifier() &&
12000 NewFD->setInvalidDecl();
12001 return Redeclaration;
12002 }
12003
12004 // In C++, check default arguments now that we have merged decls. Unless
12005 // the lexical context is the class, because in this case this is done
12006 // during delayed parsing anyway.
12007 if (!CurContext->isRecord())
12009
12010 // If this function is declared as being extern "C", then check to see if
12011 // the function returns a UDT (class, struct, or union type) that is not C
12012 // compatible, and if it does, warn the user.
12013 // But, issue any diagnostic on the first declaration only.
12014 if (Previous.empty() && NewFD->isExternC()) {
12015 QualType R = NewFD->getReturnType();
12016 if (R->isIncompleteType() && !R->isVoidType())
12017 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12018 << NewFD << R;
12019 else if (!R.isPODType(Context) && !R->isVoidType() &&
12021 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12022 }
12023
12024 // C++1z [dcl.fct]p6:
12025 // [...] whether the function has a non-throwing exception-specification
12026 // [is] part of the function type
12027 //
12028 // This results in an ABI break between C++14 and C++17 for functions whose
12029 // declared type includes an exception-specification in a parameter or
12030 // return type. (Exception specifications on the function itself are OK in
12031 // most cases, and exception specifications are not permitted in most other
12032 // contexts where they could make it into a mangling.)
12033 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12034 auto HasNoexcept = [&](QualType T) -> bool {
12035 // Strip off declarator chunks that could be between us and a function
12036 // type. We don't need to look far, exception specifications are very
12037 // restricted prior to C++17.
12038 if (auto *RT = T->getAs<ReferenceType>())
12039 T = RT->getPointeeType();
12040 else if (T->isAnyPointerType())
12041 T = T->getPointeeType();
12042 else if (auto *MPT = T->getAs<MemberPointerType>())
12043 T = MPT->getPointeeType();
12044 if (auto *FPT = T->getAs<FunctionProtoType>())
12045 if (FPT->isNothrow())
12046 return true;
12047 return false;
12048 };
12049
12050 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12051 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12052 for (QualType T : FPT->param_types())
12053 AnyNoexcept |= HasNoexcept(T);
12054 if (AnyNoexcept)
12055 Diag(NewFD->getLocation(),
12056 diag::warn_cxx17_compat_exception_spec_in_signature)
12057 << NewFD;
12058 }
12059
12060 if (!Redeclaration && LangOpts.CUDA)
12062 }
12063 return Redeclaration;
12064}
12065
12067 // C++11 [basic.start.main]p3:
12068 // A program that [...] declares main to be inline, static or
12069 // constexpr is ill-formed.
12070 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12071 // appear in a declaration of main.
12072 // static main is not an error under C99, but we should warn about it.
12073 // We accept _Noreturn main as an extension.
12074 if (FD->getStorageClass() == SC_Static)
12076 ? diag::err_static_main : diag::warn_static_main)
12078 if (FD->isInlineSpecified())
12079 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12081 if (DS.isNoreturnSpecified()) {
12082 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12083 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12084 Diag(NoreturnLoc, diag::ext_noreturn_main);
12085 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12086 << FixItHint::CreateRemoval(NoreturnRange);
12087 }
12088 if (FD->isConstexpr()) {
12089 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12090 << FD->isConsteval()
12093 }
12094
12095 if (getLangOpts().OpenCL) {
12096 Diag(FD->getLocation(), diag::err_opencl_no_main)
12097 << FD->hasAttr<OpenCLKernelAttr>();
12098 FD->setInvalidDecl();
12099 return;
12100 }
12101
12102 // Functions named main in hlsl are default entries, but don't have specific
12103 // signatures they are required to conform to.
12104 if (getLangOpts().HLSL)
12105 return;
12106
12107 QualType T = FD->getType();
12108 assert(T->isFunctionType() && "function decl is not of function type");
12109 const FunctionType* FT = T->castAs<FunctionType>();
12110
12111 // Set default calling convention for main()
12112 if (FT->getCallConv() != CC_C) {
12114 FD->setType(QualType(FT, 0));
12115 T = Context.getCanonicalType(FD->getType());
12116 }
12117
12119 // In C with GNU extensions we allow main() to have non-integer return
12120 // type, but we should warn about the extension, and we disable the
12121 // implicit-return-zero rule.
12122
12123 // GCC in C mode accepts qualified 'int'.
12125 FD->setHasImplicitReturnZero(true);
12126 else {
12127 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12128 SourceRange RTRange = FD->getReturnTypeSourceRange();
12129 if (RTRange.isValid())
12130 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12131 << FixItHint::CreateReplacement(RTRange, "int");
12132 }
12133 } else {
12134 // In C and C++, main magically returns 0 if you fall off the end;
12135 // set the flag which tells us that.
12136 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12137
12138 // All the standards say that main() should return 'int'.
12140 FD->setHasImplicitReturnZero(true);
12141 else {
12142 // Otherwise, this is just a flat-out error.
12143 SourceRange RTRange = FD->getReturnTypeSourceRange();
12144 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12145 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12146 : FixItHint());
12147 FD->setInvalidDecl(true);
12148 }
12149 }
12150
12151 // Treat protoless main() as nullary.
12152 if (isa<FunctionNoProtoType>(FT)) return;
12153
12155 unsigned nparams = FTP->getNumParams();
12156 assert(FD->getNumParams() == nparams);
12157
12158 bool HasExtraParameters = (nparams > 3);
12159
12160 if (FTP->isVariadic()) {
12161 Diag(FD->getLocation(), diag::ext_variadic_main);
12162 // FIXME: if we had information about the location of the ellipsis, we
12163 // could add a FixIt hint to remove it as a parameter.
12164 }
12165
12166 // Darwin passes an undocumented fourth argument of type char**. If
12167 // other platforms start sprouting these, the logic below will start
12168 // getting shifty.
12169 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12170 HasExtraParameters = false;
12171
12172 if (HasExtraParameters) {
12173 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12174 FD->setInvalidDecl(true);
12175 nparams = 3;
12176 }
12177
12178 // FIXME: a lot of the following diagnostics would be improved
12179 // if we had some location information about types.
12180
12181 QualType CharPP =
12183 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12184
12185 for (unsigned i = 0; i < nparams; ++i) {
12186 QualType AT = FTP->getParamType(i);
12187
12188 bool mismatch = true;
12189
12191 mismatch = false;
12192 else if (Expected[i] == CharPP) {
12193 // As an extension, the following forms are okay:
12194 // char const **
12195 // char const * const *
12196 // char * const *
12197
12199 const PointerType* PT;
12200 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12201 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12203 Context.CharTy)) {
12204 qs.removeConst();
12205 mismatch = !qs.empty();
12206 }
12207 }
12208
12209 if (mismatch) {
12210 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12211 // TODO: suggest replacing given type with expected type
12212 FD->setInvalidDecl(true);
12213 }
12214 }
12215
12216 if (nparams == 1 && !FD->isInvalidDecl()) {
12217 Diag(FD->getLocation(), diag::warn_main_one_arg);
12218 }
12219
12220 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12221 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12222 FD->setInvalidDecl();
12223 }
12224}
12225
12226static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12227
12228 // Default calling convention for main and wmain is __cdecl
12229 if (FD->getName() == "main" || FD->getName() == "wmain")
12230 return false;
12231
12232 // Default calling convention for MinGW is __cdecl
12233 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12234 if (T.isWindowsGNUEnvironment())
12235 return false;
12236
12237 // Default calling convention for WinMain, wWinMain and DllMain
12238 // is __stdcall on 32 bit Windows
12239 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12240 return true;
12241
12242 return false;
12243}
12244
12246 QualType T = FD->getType();
12247 assert(T->isFunctionType() && "function decl is not of function type");
12248 const FunctionType *FT = T->castAs<FunctionType>();
12249
12250 // Set an implicit return of 'zero' if the function can return some integral,
12251 // enumeration, pointer or nullptr type.
12255 // DllMain is exempt because a return value of zero means it failed.
12256 if (FD->getName() != "DllMain")
12257 FD->setHasImplicitReturnZero(true);
12258
12259 // Explicity specified calling conventions are applied to MSVC entry points
12260 if (!hasExplicitCallingConv(T)) {
12261 if (isDefaultStdCall(FD, *this)) {
12262 if (FT->getCallConv() != CC_X86StdCall) {
12265 FD->setType(QualType(FT, 0));
12266 }
12267 } else if (FT->getCallConv() != CC_C) {
12270 FD->setType(QualType(FT, 0));
12271 }
12272 }
12273
12274 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12275 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12276 FD->setInvalidDecl();
12277 }
12278}
12279
12282 auto const Triple = TargetInfo.getTriple();
12283 switch (Triple.getEnvironment()) {
12284 default:
12285 // FIXME: check all shader profiles.
12286 break;
12287 case llvm::Triple::EnvironmentType::Compute:
12288 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12289 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12290 << Triple.getEnvironmentName();
12291 FD->setInvalidDecl();
12292 }
12293 break;
12294 }
12295
12296 for (const auto *Param : FD->parameters()) {
12297 if (!Param->hasAttr<HLSLAnnotationAttr>()) {
12298 // FIXME: Handle struct parameters where annotations are on struct fields.
12299 // See: https://github.com/llvm/llvm-project/issues/57875
12300 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12301 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12302 FD->setInvalidDecl();
12303 }
12304 }
12305 // FIXME: Verify return type semantic annotation.
12306}
12307
12309 // FIXME: Need strict checking. In C89, we need to check for
12310 // any assignment, increment, decrement, function-calls, or
12311 // commas outside of a sizeof. In C99, it's the same list,
12312 // except that the aforementioned are allowed in unevaluated
12313 // expressions. Everything else falls under the
12314 // "may accept other forms of constant expressions" exception.
12315 //
12316 // Regular C++ code will not end up here (exceptions: language extensions,
12317 // OpenCL C++ etc), so the constant expression rules there don't matter.
12318 if (Init->isValueDependent()) {
12319 assert(Init->containsErrors() &&
12320 "Dependent code should only occur in error-recovery path.");
12321 return true;
12322 }
12323 const Expr *Culprit;
12324 if (Init->isConstantInitializer(Context, false, &Culprit))
12325 return false;
12326 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12327 << Culprit->getSourceRange();
12328 return true;
12329}
12330
12331namespace {
12332 // Visits an initialization expression to see if OrigDecl is evaluated in
12333 // its own initialization and throws a warning if it does.
12334 class SelfReferenceChecker
12335 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12336 Sema &S;
12337 Decl *OrigDecl;
12338 bool isRecordType;
12339 bool isPODType;
12340 bool isReferenceType;
12341
12342 bool isInitList;
12343 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12344
12345 public:
12347
12348 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12349 S(S), OrigDecl(OrigDecl) {
12350 isPODType = false;
12351 isRecordType = false;
12352 isReferenceType = false;
12353 isInitList = false;
12354 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12355 isPODType = VD->getType().isPODType(S.Context);
12356 isRecordType = VD->getType()->isRecordType();
12357 isReferenceType = VD->getType()->isReferenceType();
12358 }
12359 }
12360
12361 // For most expressions, just call the visitor. For initializer lists,
12362 // track the index of the field being initialized since fields are
12363 // initialized in order allowing use of previously initialized fields.
12364 void CheckExpr(Expr *E) {
12365 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12366 if (!InitList) {
12367 Visit(E);
12368 return;
12369 }
12370
12371 // Track and increment the index here.
12372 isInitList = true;
12373 InitFieldIndex.push_back(0);
12374 for (auto *Child : InitList->children()) {
12375 CheckExpr(cast<Expr>(Child));
12376 ++InitFieldIndex.back();
12377 }
12378 InitFieldIndex.pop_back();
12379 }
12380
12381 // Returns true if MemberExpr is checked and no further checking is needed.
12382 // Returns false if additional checking is required.
12383 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12385 Expr *Base = E;
12386 bool ReferenceField = false;
12387
12388 // Get the field members used.
12389 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12390 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12391 if (!FD)
12392 return false;
12393 Fields.push_back(FD);
12394 if (FD->getType()->isReferenceType())
12395 ReferenceField = true;
12396 Base = ME->getBase()->IgnoreParenImpCasts();
12397 }
12398
12399 // Keep checking only if the base Decl is the same.
12400 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12401 if (!DRE || DRE->getDecl() != OrigDecl)
12402 return false;
12403
12404 // A reference field can be bound to an unininitialized field.
12405 if (CheckReference && !ReferenceField)
12406 return true;
12407
12408 // Convert FieldDecls to their index number.
12409 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12410 for (const FieldDecl *I : llvm::reverse(Fields))
12411 UsedFieldIndex.push_back(I->getFieldIndex());
12412
12413 // See if a warning is needed by checking the first difference in index
12414 // numbers. If field being used has index less than the field being
12415 // initialized, then the use is safe.
12416 for (auto UsedIter = UsedFieldIndex.begin(),
12417 UsedEnd = UsedFieldIndex.end(),
12418 OrigIter = InitFieldIndex.begin(),
12419 OrigEnd = InitFieldIndex.end();
12420 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12421 if (*UsedIter < *OrigIter)
12422 return true;
12423 if (*UsedIter > *OrigIter)
12424 break;
12425 }
12426
12427 // TODO: Add a different warning which will print the field names.
12428 HandleDeclRefExpr(DRE);
12429 return true;
12430 }
12431
12432 // For most expressions, the cast is directly above the DeclRefExpr.
12433 // For conditional operators, the cast can be outside the conditional
12434 // operator if both expressions are DeclRefExpr's.
12435 void HandleValue(Expr *E) {
12436 E = E->IgnoreParens();
12437 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12438 HandleDeclRefExpr(DRE);
12439 return;
12440 }
12441
12442 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12443 Visit(CO->getCond());
12444 HandleValue(CO->getTrueExpr());
12445 HandleValue(CO->getFalseExpr());
12446 return;
12447 }
12448
12449 if (BinaryConditionalOperator *BCO =
12450 dyn_cast<BinaryConditionalOperator>(E)) {
12451 Visit(BCO->getCond());
12452 HandleValue(BCO->getFalseExpr());
12453 return;
12454 }
12455
12456 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12457 HandleValue(OVE->getSourceExpr());
12458 return;
12459 }
12460
12461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12462 if (BO->getOpcode() == BO_Comma) {
12463 Visit(BO->getLHS());
12464 HandleValue(BO->getRHS());
12465 return;
12466 }
12467 }
12468
12469 if (isa<MemberExpr>(E)) {
12470 if (isInitList) {
12471 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12472 false /*CheckReference*/))
12473 return;
12474 }
12475
12477 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12478 // Check for static member variables and don't warn on them.
12479 if (!isa<FieldDecl>(ME->getMemberDecl()))
12480 return;
12481 Base = ME->getBase()->IgnoreParenImpCasts();
12482 }
12483 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12484 HandleDeclRefExpr(DRE);
12485 return;
12486 }
12487
12488 Visit(E);
12489 }
12490
12491 // Reference types not handled in HandleValue are handled here since all
12492 // uses of references are bad, not just r-value uses.
12493 void VisitDeclRefExpr(DeclRefExpr *E) {
12494 if (isReferenceType)
12495 HandleDeclRefExpr(E);
12496 }
12497
12498 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12499 if (E->getCastKind() == CK_LValueToRValue) {
12500 HandleValue(E->getSubExpr());
12501 return;
12502 }
12503
12504 Inherited::VisitImplicitCastExpr(E);
12505 }
12506
12507 void VisitMemberExpr(MemberExpr *E) {
12508 if (isInitList) {
12509 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12510 return;
12511 }
12512
12513 // Don't warn on arrays since they can be treated as pointers.
12514 if (E->getType()->canDecayToPointerType()) return;
12515
12516 // Warn when a non-static method call is followed by non-static member
12517 // field accesses, which is followed by a DeclRefExpr.
12518 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12519 bool Warn = (MD && !MD->isStatic());
12521 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12522 if (!isa<FieldDecl>(ME->getMemberDecl()))
12523 Warn = false;
12524 Base = ME->getBase()->IgnoreParenImpCasts();
12525 }
12526
12527 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12528 if (Warn)
12529 HandleDeclRefExpr(DRE);
12530 return;
12531 }
12532
12533 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12534 // Visit that expression.
12535 Visit(Base);
12536 }
12537
12538 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12539 Expr *Callee = E->getCallee();
12540
12541 if (isa<UnresolvedLookupExpr>(Callee))
12542 return Inherited::VisitCXXOperatorCallExpr(E);
12543
12544 Visit(Callee);
12545 for (auto Arg: E->arguments())
12546 HandleValue(Arg->IgnoreParenImpCasts());
12547 }
12548
12549 void VisitUnaryOperator(UnaryOperator *E) {
12550 // For POD record types, addresses of its own members are well-defined.
12551 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12552 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12553 if (!isPODType)
12554 HandleValue(E->getSubExpr());
12555 return;
12556 }
12557
12558 if (E->isIncrementDecrementOp()) {
12559 HandleValue(E->getSubExpr());
12560 return;
12561 }
12562
12563 Inherited::VisitUnaryOperator(E);
12564 }
12565
12566 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12567
12568 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12569 if (E->getConstructor()->isCopyConstructor()) {
12570 Expr *ArgExpr = E->getArg(0);
12571 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12572 if (ILE->getNumInits() == 1)
12573 ArgExpr = ILE->getInit(0);
12574 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12575 if (ICE->getCastKind() == CK_NoOp)
12576 ArgExpr = ICE->getSubExpr();
12577 HandleValue(ArgExpr);
12578 return;
12579 }
12580 Inherited::VisitCXXConstructExpr(E);
12581 }
12582
12583 void VisitCallExpr(CallExpr *E) {
12584 // Treat std::move as a use.
12585 if (E->isCallToStdMove()) {
12586 HandleValue(E->getArg(0));
12587 return;
12588 }
12589
12590 Inherited::VisitCallExpr(E);
12591 }
12592
12593 void VisitBinaryOperator(BinaryOperator *E) {
12594 if (E->isCompoundAssignmentOp()) {
12595 HandleValue(E->getLHS());
12596 Visit(E->getRHS());
12597 return;
12598 }
12599
12600 Inherited::VisitBinaryOperator(E);
12601 }
12602
12603 // A custom visitor for BinaryConditionalOperator is needed because the
12604 // regular visitor would check the condition and true expression separately
12605 // but both point to the same place giving duplicate diagnostics.
12606 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12607 Visit(E->getCond());
12608 Visit(E->getFalseExpr());
12609 }
12610
12611 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12612 Decl* ReferenceDecl = DRE->getDecl();
12613 if (OrigDecl != ReferenceDecl) return;
12614 unsigned diag;
12615 if (isReferenceType) {
12616 diag = diag::warn_uninit_self_reference_in_reference_init;
12617 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12618 diag = diag::warn_static_self_reference_in_init;
12619 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12620 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12621 DRE->getDecl()->getType()->isRecordType()) {
12622 diag = diag::warn_uninit_self_reference_in_init;
12623 } else {
12624 // Local variables will be handled by the CFG analysis.
12625 return;
12626 }
12627
12628 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12629 S.PDiag(diag)
12630 << DRE->getDecl() << OrigDecl->getLocation()
12631 << DRE->getSourceRange());
12632 }
12633 };
12634
12635 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12636 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12637 bool DirectInit) {
12638 // Parameters arguments are occassionially constructed with itself,
12639 // for instance, in recursive functions. Skip them.
12640 if (isa<ParmVarDecl>(OrigDecl))
12641 return;
12642
12643 E = E->IgnoreParens();
12644
12645 // Skip checking T a = a where T is not a record or reference type.
12646 // Doing so is a way to silence uninitialized warnings.
12647 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12648 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12649 if (ICE->getCastKind() == CK_LValueToRValue)
12650 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12651 if (DRE->getDecl() == OrigDecl)
12652 return;
12653
12654 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12655 }
12656} // end anonymous namespace
12657
12658namespace {
12659 // Simple wrapper to add the name of a variable or (if no variable is
12660 // available) a DeclarationName into a diagnostic.
12661 struct VarDeclOrName {
12662 VarDecl *VDecl;
12663 DeclarationName Name;
12664
12665 friend const Sema::SemaDiagnosticBuilder &
12666 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12667 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12668 }
12669 };
12670} // end anonymous namespace
12671
12674 TypeSourceInfo *TSI,
12675 SourceRange Range, bool DirectInit,
12676 Expr *Init) {
12677 bool IsInitCapture = !VDecl;
12678 assert((!VDecl || !VDecl->isInitCapture()) &&
12679 "init captures are expected to be deduced prior to initialization");
12680
12681 VarDeclOrName VN{VDecl, Name};
12682
12683 DeducedType *Deduced = Type->getContainedDeducedType();
12684 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12685
12686 // C++11 [dcl.spec.auto]p3
12687 if (!Init) {
12688 assert(VDecl && "no init for init capture deduction?");
12689
12690 // Except for class argument deduction, and then for an initializing
12691 // declaration only, i.e. no static at class scope or extern.
12692 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12693 VDecl->hasExternalStorage() ||
12694 VDecl->isStaticDataMember()) {
12695 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12696 << VDecl->getDeclName() << Type;
12697 return QualType();
12698 }
12699 }
12700
12701 ArrayRef<Expr*> DeduceInits;
12702 if (Init)
12703 DeduceInits = Init;
12704
12705 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12706 if (DirectInit && PL)
12707 DeduceInits = PL->exprs();
12708
12709 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12710 assert(VDecl && "non-auto type for init capture deduction?");
12713 VDecl->getLocation(), DirectInit, Init);
12714 // FIXME: Initialization should not be taking a mutable list of inits.
12715 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12716 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12717 InitsCopy, PL);
12718 }
12719
12720 if (DirectInit) {
12721 if (auto *IL = dyn_cast<InitListExpr>(Init))
12722 DeduceInits = IL->inits();
12723 }
12724
12725 // Deduction only works if we have exactly one source expression.
12726 if (DeduceInits.empty()) {
12727 // It isn't possible to write this directly, but it is possible to
12728 // end up in this situation with "auto x(some_pack...);"
12729 Diag(Init->getBeginLoc(), IsInitCapture
12730 ? diag::err_init_capture_no_expression
12731 : diag::err_auto_var_init_no_expression)
12732 << VN << Type << Range;
12733 return QualType();
12734 }
12735
12736 if (DeduceInits.size() > 1) {
12737 Diag(DeduceInits[1]->getBeginLoc(),
12738 IsInitCapture ? diag::err_init_capture_multiple_expressions
12739 : diag::err_auto_var_init_multiple_expressions)
12740 << VN << Type << Range;
12741 return QualType();
12742 }
12743
12744 Expr *DeduceInit = DeduceInits[0];
12745 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12746 Diag(Init->getBeginLoc(), IsInitCapture
12747 ? diag::err_init_capture_paren_braces
12748 : diag::err_auto_var_init_paren_braces)
12749 << isa<InitListExpr>(Init) << VN << Type << Range;
12750 return QualType();
12751 }
12752
12753 // Expressions default to 'id' when we're in a debugger.
12754 bool DefaultedAnyToId = false;
12755 if (getLangOpts().DebuggerCastResultToId &&
12756 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12758 if (Result.isInvalid()) {
12759 return QualType();
12760 }
12761 Init = Result.get();
12762 DefaultedAnyToId = true;
12763 }
12764
12765 // C++ [dcl.decomp]p1:
12766 // If the assignment-expression [...] has array type A and no ref-qualifier
12767 // is present, e has type cv A
12768 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12770 DeduceInit->getType()->isConstantArrayType())
12771 return Context.getQualifiedType(DeduceInit->getType(),
12772 Type.getQualifiers());
12773
12774 QualType DeducedType;
12775 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12777 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12779 if (!IsInitCapture)
12780 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12781 else if (isa<InitListExpr>(Init))
12782 Diag(Range.getBegin(),
12783 diag::err_init_capture_deduction_failure_from_init_list)
12784 << VN
12785 << (DeduceInit->getType().isNull() ? TSI->getType()
12786 : DeduceInit->getType())
12787 << DeduceInit->getSourceRange();
12788 else
12789 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12790 << VN << TSI->getType()
12791 << (DeduceInit->getType().isNull() ? TSI->getType()
12792 : DeduceInit->getType())
12793 << DeduceInit->getSourceRange();
12794 }
12795
12796 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12797 // 'id' instead of a specific object type prevents most of our usual
12798 // checks.
12799 // We only want to warn outside of template instantiations, though:
12800 // inside a template, the 'id' could have come from a parameter.
12801 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12802 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12803 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12804 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12805 }
12806
12807 return DeducedType;
12808}
12809
12811 Expr *Init) {
12812 assert(!Init || !Init->containsErrors());
12814 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12815 VDecl->getSourceRange(), DirectInit, Init);
12816 if (DeducedType.isNull()) {
12817 VDecl->setInvalidDecl();
12818 return true;
12819 }
12820
12821 VDecl->setType(DeducedType);
12822 assert(VDecl->isLinkageValid());
12823
12824 // In ARC, infer lifetime.
12825 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12826 VDecl->setInvalidDecl();
12827
12828 if (getLangOpts().OpenCL)
12830
12831 // If this is a redeclaration, check that the type we just deduced matches
12832 // the previously declared type.
12833 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12834 // We never need to merge the type, because we cannot form an incomplete
12835 // array of auto, nor deduce such a type.
12836 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12837 }
12838
12839 // Check the deduced type is valid for a variable declaration.
12841 return VDecl->isInvalidDecl();
12842}
12843
12845 SourceLocation Loc) {
12846 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12847 Init = EWC->getSubExpr();
12848
12849 if (auto *CE = dyn_cast<ConstantExpr>(Init))
12850 Init = CE->getSubExpr();
12851
12852 QualType InitType = Init->getType();
12855 "shouldn't be called if type doesn't have a non-trivial C struct");
12856 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12857 for (auto *I : ILE->inits()) {
12858 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12859 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12860 continue;
12861 SourceLocation SL = I->getExprLoc();
12862 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12863 }
12864 return;
12865 }
12866
12867 if (isa<ImplicitValueInitExpr>(Init)) {
12870 NTCUK_Init);
12871 } else {
12872 // Assume all other explicit initializers involving copying some existing
12873 // object.
12874 // TODO: ignore any explicit initializers where we can guarantee
12875 // copy-elision.
12878 }
12879}
12880
12881namespace {
12882
12883bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12884 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12885 // in the source code or implicitly by the compiler if it is in a union
12886 // defined in a system header and has non-trivial ObjC ownership
12887 // qualifications. We don't want those fields to participate in determining
12888 // whether the containing union is non-trivial.
12889 return FD->hasAttr<UnavailableAttr>();
12890}
12891
12892struct DiagNonTrivalCUnionDefaultInitializeVisitor
12893 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12894 void> {
12895 using Super =
12896 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12897 void>;
12898
12899 DiagNonTrivalCUnionDefaultInitializeVisitor(
12900 QualType OrigTy, SourceLocation OrigLoc,
12901 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12902 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12903
12904 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12905 const FieldDecl *FD, bool InNonTrivialUnion) {
12906 if (const auto *AT = S.Context.getAsArrayType(QT))
12907 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12908 InNonTrivialUnion);
12909 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12910 }
12911
12912 void visitARCStrong(QualType QT, const FieldDecl *FD,
12913 bool InNonTrivialUnion) {
12914 if (InNonTrivialUnion)
12915 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12916 << 1 << 0 << QT << FD->getName();
12917 }
12918
12919 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12920 if (InNonTrivialUnion)
12921 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12922 << 1 << 0 << QT << FD->getName();
12923 }
12924
12925 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12926 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12927 if (RD->isUnion()) {
12928 if (OrigLoc.isValid()) {
12929 bool IsUnion = false;
12930 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12931 IsUnion = OrigRD->isUnion();
12932 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12933 << 0 << OrigTy << IsUnion << UseContext;
12934 // Reset OrigLoc so that this diagnostic is emitted only once.
12935 OrigLoc = SourceLocation();
12936 }
12937 InNonTrivialUnion = true;
12938 }
12939
12940 if (InNonTrivialUnion)
12941 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12942 << 0 << 0 << QT.getUnqualifiedType() << "";
12943
12944 for (const FieldDecl *FD : RD->fields())
12945 if (!shouldIgnoreForRecordTriviality(FD))
12946 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12947 }
12948
12949 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12950
12951 // The non-trivial C union type or the struct/union type that contains a
12952 // non-trivial C union.
12953 QualType OrigTy;
12954 SourceLocation OrigLoc;
12956 Sema &S;
12957};
12958
12959struct DiagNonTrivalCUnionDestructedTypeVisitor
12960 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12961 using Super =
12963
12964 DiagNonTrivalCUnionDestructedTypeVisitor(
12965 QualType OrigTy, SourceLocation OrigLoc,
12966 Sema::NonTrivialCUnionContext UseContext, Sema &S)
12967 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12968
12969 void visitWithKind(QualType::DestructionKind DK, QualType QT,
12970 const FieldDecl *FD, bool InNonTrivialUnion) {
12971 if (const auto *AT = S.Context.getAsArrayType(QT))
12972 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12973 InNonTrivialUnion);
12974 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12975 }
12976
12977 void visitARCStrong(QualType QT, const FieldDecl *FD,
12978 bool InNonTrivialUnion) {
12979 if (InNonTrivialUnion)
12980 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12981 << 1 << 1 << QT << FD->getName();
12982 }
12983
12984 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12985 if (InNonTrivialUnion)
12986 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12987 << 1 << 1 << QT << FD->getName();
12988 }
12989
12990 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12991 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12992 if (RD->isUnion()) {
12993 if (OrigLoc.isValid()) {
12994 bool IsUnion = false;
12995 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12996 IsUnion = OrigRD->isUnion();
12997 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12998 << 1 << OrigTy << IsUnion << UseContext;
12999 // Reset OrigLoc so that this diagnostic is emitted only once.
13000 OrigLoc = SourceLocation();
13001 }
13002 InNonTrivialUnion = true;
13003 }
13004
13005 if (InNonTrivialUnion)
13006 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13007 << 0 << 1 << QT.getUnqualifiedType() << "";
13008
13009 for (const FieldDecl *FD : RD->fields())
13010 if (!shouldIgnoreForRecordTriviality(FD))
13011 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13012 }
13013
13014 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13015 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13016 bool InNonTrivialUnion) {}
13017
13018 // The non-trivial C union type or the struct/union type that contains a
13019 // non-trivial C union.
13020 QualType OrigTy;
13021 SourceLocation OrigLoc;
13023 Sema &S;
13024};
13025
13026struct DiagNonTrivalCUnionCopyVisitor
13027 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13029
13030 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13032 Sema &S)
13033 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13034
13035 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13036 const FieldDecl *FD, bool InNonTrivialUnion) {
13037 if (const auto *AT = S.Context.getAsArrayType(QT))
13038 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13039 InNonTrivialUnion);
13040 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13041 }
13042
13043 void visitARCStrong(QualType QT, const FieldDecl *FD,
13044 bool InNonTrivialUnion) {
13045 if (InNonTrivialUnion)
13046 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13047 << 1 << 2 << QT << FD->getName();
13048 }
13049
13050 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13051 if (InNonTrivialUnion)
13052 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13053 << 1 << 2 << QT << FD->getName();
13054 }
13055
13056 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13057 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13058 if (RD->isUnion()) {
13059 if (OrigLoc.isValid()) {
13060 bool IsUnion = false;
13061 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13062 IsUnion = OrigRD->isUnion();
13063 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13064 << 2 << OrigTy << IsUnion << UseContext;
13065 // Reset OrigLoc so that this diagnostic is emitted only once.
13066 OrigLoc = SourceLocation();
13067 }
13068 InNonTrivialUnion = true;
13069 }
13070
13071 if (InNonTrivialUnion)
13072 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13073 << 0 << 2 << QT.getUnqualifiedType() << "";
13074
13075 for (const FieldDecl *FD : RD->fields())
13076 if (!shouldIgnoreForRecordTriviality(FD))
13077 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13078 }
13079
13080 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13081 const FieldDecl *FD, bool InNonTrivialUnion) {}
13082 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13083 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13084 bool InNonTrivialUnion) {}
13085
13086 // The non-trivial C union type or the struct/union type that contains a
13087 // non-trivial C union.
13088 QualType OrigTy;
13089 SourceLocation OrigLoc;
13091 Sema &S;
13092};
13093
13094} // namespace
13095
13097 NonTrivialCUnionContext UseContext,
13098 unsigned NonTrivialKind) {
13102 "shouldn't be called if type doesn't have a non-trivial C union");
13103
13104 if ((NonTrivialKind & NTCUK_Init) &&
13106 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13107 .visit(QT, nullptr, false);
13108 if ((NonTrivialKind & NTCUK_Destruct) &&
13110 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13111 .visit(QT, nullptr, false);
13112 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13113 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13114 .visit(QT, nullptr, false);
13115}
13116
13117/// AddInitializerToDecl - Adds the initializer Init to the
13118/// declaration dcl. If DirectInit is true, this is C++ direct
13119/// initialization rather than copy initialization.
13120void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13121 // If there is no declaration, there was an error parsing it. Just ignore
13122 // the initializer.
13123 if (!RealDecl || RealDecl->isInvalidDecl()) {
13124 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13125 return;
13126 }
13127
13128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13129 // Pure-specifiers are handled in ActOnPureSpecifier.
13130 Diag(Method->getLocation(), diag::err_member_function_initialization)
13131 << Method->getDeclName() << Init->getSourceRange();
13132 Method->setInvalidDecl();
13133 return;
13134 }
13135
13136 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13137 if (!VDecl) {
13138 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13139 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13140 RealDecl->setInvalidDecl();
13141 return;
13142 }
13143
13144 // WebAssembly tables can't be used to initialise a variable.
13145 if (Init && !Init->getType().isNull() &&
13146 Init->getType()->isWebAssemblyTableType()) {
13147 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13148 VDecl->setInvalidDecl();
13149 return;
13150 }
13151
13152 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13153 if (VDecl->getType()->isUndeducedType()) {
13154 // Attempt typo correction early so that the type of the init expression can
13155 // be deduced based on the chosen correction if the original init contains a
13156 // TypoExpr.
13157 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13158 if (!Res.isUsable()) {
13159 // There are unresolved typos in Init, just drop them.
13160 // FIXME: improve the recovery strategy to preserve the Init.
13161 RealDecl->setInvalidDecl();
13162 return;
13163 }
13164 if (Res.get()->containsErrors()) {
13165 // Invalidate the decl as we don't know the type for recovery-expr yet.
13166 RealDecl->setInvalidDecl();
13167 VDecl->setInit(Res.get());
13168 return;
13169 }
13170 Init = Res.get();
13171
13172 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13173 return;
13174 }
13175
13176 // dllimport cannot be used on variable definitions.
13177 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13178 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13179 VDecl->setInvalidDecl();
13180 return;
13181 }
13182
13183 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13184 // the identifier has external or internal linkage, the declaration shall
13185 // have no initializer for the identifier.
13186 // C++14 [dcl.init]p5 is the same restriction for C++.
13187 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13188 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13189 VDecl->setInvalidDecl();
13190 return;
13191 }
13192
13193 if (!VDecl->getType()->isDependentType()) {
13194 // A definition must end up with a complete type, which means it must be
13195 // complete with the restriction that an array type might be completed by
13196 // the initializer; note that later code assumes this restriction.
13197 QualType BaseDeclType = VDecl->getType();
13198 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13199 BaseDeclType = Array->getElementType();
13200 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13201 diag::err_typecheck_decl_incomplete_type)) {
13202 RealDecl->setInvalidDecl();
13203 return;
13204 }
13205
13206 // The variable can not have an abstract class type.
13207 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13208 diag::err_abstract_type_in_decl,
13210 VDecl->setInvalidDecl();
13211 }
13212
13213 // C++ [module.import/6] external definitions are not permitted in header
13214 // units.
13215 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13216 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13218 !VDecl->isInline() && !VDecl->isTemplated() &&
13219 !isa<VarTemplateSpecializationDecl>(VDecl)) {
13220 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13221 VDecl->setInvalidDecl();
13222 }
13223
13224 // If adding the initializer will turn this declaration into a definition,
13225 // and we already have a definition for this variable, diagnose or otherwise
13226 // handle the situation.
13227 if (VarDecl *Def = VDecl->getDefinition())
13228 if (Def != VDecl &&
13229 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13231 checkVarDeclRedefinition(Def, VDecl))
13232 return;
13233
13234 if (getLangOpts().CPlusPlus) {
13235 // C++ [class.static.data]p4
13236 // If a static data member is of const integral or const
13237 // enumeration type, its declaration in the class definition can
13238 // specify a constant-initializer which shall be an integral
13239 // constant expression (5.19). In that case, the member can appear
13240 // in integral constant expressions. The member shall still be
13241 // defined in a namespace scope if it is used in the program and the
13242 // namespace scope definition shall not contain an initializer.
13243 //
13244 // We already performed a redefinition check above, but for static
13245 // data members we also need to check whether there was an in-class
13246 // declaration with an initializer.
13247 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13248 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13249 << VDecl->getDeclName();
13250 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13251 diag::note_previous_initializer)
13252 << 0;
13253 return;
13254 }
13255
13256 if (VDecl->hasLocalStorage())
13258
13260 VDecl->setInvalidDecl();
13261 return;
13262 }
13263 }
13264
13265 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13266 // a kernel function cannot be initialized."
13267 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13268 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13269 VDecl->setInvalidDecl();
13270 return;
13271 }
13272
13273 // The LoaderUninitialized attribute acts as a definition (of undef).
13274 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13275 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13276 VDecl->setInvalidDecl();
13277 return;
13278 }
13279
13280 // Get the decls type and save a reference for later, since
13281 // CheckInitializerTypes may change it.
13282 QualType DclT = VDecl->getType(), SavT = DclT;
13283
13284 // Expressions default to 'id' when we're in a debugger
13285 // and we are assigning it to a variable of Objective-C pointer type.
13286 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13287 Init->getType() == Context.UnknownAnyTy) {
13289 if (Result.isInvalid()) {
13290 VDecl->setInvalidDecl();
13291 return;
13292 }
13293 Init = Result.get();
13294 }
13295
13296 // Perform the initialization.
13297 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13298 bool IsParenListInit = false;
13299 if (!VDecl->isInvalidDecl()) {
13302 VDecl->getLocation(), DirectInit, Init);
13303
13304 MultiExprArg Args = Init;
13305 if (CXXDirectInit)
13306 Args = MultiExprArg(CXXDirectInit->getExprs(),
13307 CXXDirectInit->getNumExprs());
13308
13309 // Try to correct any TypoExprs in the initialization arguments.
13310 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13312 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13313 [this, Entity, Kind](Expr *E) {
13314 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13315 return Init.Failed() ? ExprError() : E;
13316 });
13317 if (Res.isInvalid()) {
13318 VDecl->setInvalidDecl();
13319 } else if (Res.get() != Args[Idx]) {
13320 Args[Idx] = Res.get();
13321 }
13322 }
13323 if (VDecl->isInvalidDecl())
13324 return;
13325
13326 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13327 /*TopLevelOfInitList=*/false,
13328 /*TreatUnavailableAsInvalid=*/false);
13329 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13330 if (Result.isInvalid()) {
13331 // If the provided initializer fails to initialize the var decl,
13332 // we attach a recovery expr for better recovery.
13333 auto RecoveryExpr =
13334 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13335 if (RecoveryExpr.get())
13336 VDecl->setInit(RecoveryExpr.get());
13337 return;
13338 }
13339
13340 Init = Result.getAs<Expr>();
13341 IsParenListInit = !InitSeq.steps().empty() &&
13342 InitSeq.step_begin()->Kind ==
13344 }
13345
13346 // Check for self-references within variable initializers.
13347 // Variables declared within a function/method body (except for references)
13348 // are handled by a dataflow analysis.
13349 // This is undefined behavior in C++, but valid in C.
13350 if (getLangOpts().CPlusPlus)
13351 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13352 VDecl->getType()->isReferenceType())
13353 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13354
13355 // If the type changed, it means we had an incomplete type that was
13356 // completed by the initializer. For example:
13357 // int ary[] = { 1, 3, 5 };
13358 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13359 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13360 VDecl->setType(DclT);
13361
13362 if (!VDecl->isInvalidDecl()) {
13363 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13364
13365 if (VDecl->hasAttr<BlocksAttr>())
13366 checkRetainCycles(VDecl, Init);
13367
13368 // It is safe to assign a weak reference into a strong variable.
13369 // Although this code can still have problems:
13370 // id x = self.weakProp;
13371 // id y = self.weakProp;
13372 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13373 // paths through the function. This should be revisited if
13374 // -Wrepeated-use-of-weak is made flow-sensitive.
13375 if (FunctionScopeInfo *FSI = getCurFunction())
13376 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13378 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13379 Init->getBeginLoc()))
13380 FSI->markSafeWeakUse(Init);
13381 }
13382
13383 // The initialization is usually a full-expression.
13384 //
13385 // FIXME: If this is a braced initialization of an aggregate, it is not
13386 // an expression, and each individual field initializer is a separate
13387 // full-expression. For instance, in:
13388 //
13389 // struct Temp { ~Temp(); };
13390 // struct S { S(Temp); };
13391 // struct T { S a, b; } t = { Temp(), Temp() }
13392 //
13393 // we should destroy the first Temp before constructing the second.
13395 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13396 /*DiscardedValue*/ false, VDecl->isConstexpr());
13397 if (Result.isInvalid()) {
13398 VDecl->setInvalidDecl();
13399 return;
13400 }
13401 Init = Result.get();
13402
13403 // Attach the initializer to the decl.
13404 VDecl->setInit(Init);
13405
13406 if (VDecl->isLocalVarDecl()) {
13407 // Don't check the initializer if the declaration is malformed.
13408 if (VDecl->isInvalidDecl()) {
13409 // do nothing
13410
13411 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13412 // This is true even in C++ for OpenCL.
13413 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13414 CheckForConstantInitializer(Init, DclT);
13415
13416 // Otherwise, C++ does not restrict the initializer.
13417 } else if (getLangOpts().CPlusPlus) {
13418 // do nothing
13419
13420 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13421 // static storage duration shall be constant expressions or string literals.
13422 } else if (VDecl->getStorageClass() == SC_Static) {
13423 CheckForConstantInitializer(Init, DclT);
13424
13425 // C89 is stricter than C99 for aggregate initializers.
13426 // C89 6.5.7p3: All the expressions [...] in an initializer list
13427 // for an object that has aggregate or union type shall be
13428 // constant expressions.
13429 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13430 isa<InitListExpr>(Init)) {
13431 const Expr *Culprit;
13432 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13433 Diag(Culprit->getExprLoc(),
13434 diag::ext_aggregate_init_not_constant)
13435 << Culprit->getSourceRange();
13436 }
13437 }
13438
13439 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13440 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13441 if (VDecl->hasLocalStorage())
13442 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13443 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13444 VDecl->getLexicalDeclContext()->isRecord()) {
13445 // This is an in-class initialization for a static data member, e.g.,
13446 //
13447 // struct S {
13448 // static const int value = 17;
13449 // };
13450
13451 // C++ [class.mem]p4:
13452 // A member-declarator can contain a constant-initializer only
13453 // if it declares a static member (9.4) of const integral or
13454 // const enumeration type, see 9.4.2.
13455 //
13456 // C++11 [class.static.data]p3:
13457 // If a non-volatile non-inline const static data member is of integral
13458 // or enumeration type, its declaration in the class definition can
13459 // specify a brace-or-equal-initializer in which every initializer-clause
13460 // that is an assignment-expression is a constant expression. A static
13461 // data member of literal type can be declared in the class definition
13462 // with the constexpr specifier; if so, its declaration shall specify a
13463 // brace-or-equal-initializer in which every initializer-clause that is
13464 // an assignment-expression is a constant expression.
13465
13466 // Do nothing on dependent types.
13467 if (DclT->isDependentType()) {
13468
13469 // Allow any 'static constexpr' members, whether or not they are of literal
13470 // type. We separately check that every constexpr variable is of literal
13471 // type.
13472 } else if (VDecl->isConstexpr()) {
13473
13474 // Require constness.
13475 } else if (!DclT.isConstQualified()) {
13476 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13477 << Init->getSourceRange();
13478 VDecl->setInvalidDecl();
13479
13480 // We allow integer constant expressions in all cases.
13481 } else if (DclT->isIntegralOrEnumerationType()) {
13482 // Check whether the expression is a constant expression.
13483 SourceLocation Loc;
13485 // In C++11, a non-constexpr const static data member with an
13486 // in-class initializer cannot be volatile.
13487 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13488 else if (Init->isValueDependent())
13489 ; // Nothing to check.
13490 else if (Init->isIntegerConstantExpr(Context, &Loc))
13491 ; // Ok, it's an ICE!
13492 else if (Init->getType()->isScopedEnumeralType() &&
13493 Init->isCXX11ConstantExpr(Context))
13494 ; // Ok, it is a scoped-enum constant expression.
13495 else if (Init->isEvaluatable(Context)) {
13496 // If we can constant fold the initializer through heroics, accept it,
13497 // but report this as a use of an extension for -pedantic.
13498 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13499 << Init->getSourceRange();
13500 } else {
13501 // Otherwise, this is some crazy unknown case. Report the issue at the
13502 // location provided by the isIntegerConstantExpr failed check.
13503 Diag(Loc, diag::err_in_class_initializer_non_constant)
13504 << Init->getSourceRange();
13505 VDecl->setInvalidDecl();
13506 }
13507
13508 // We allow foldable floating-point constants as an extension.
13509 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13510 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13511 // it anyway and provide a fixit to add the 'constexpr'.
13512 if (getLangOpts().CPlusPlus11) {
13513 Diag(VDecl->getLocation(),
13514 diag::ext_in_class_initializer_float_type_cxx11)
13515 << DclT << Init->getSourceRange();
13516 Diag(VDecl->getBeginLoc(),
13517 diag::note_in_class_initializer_float_type_cxx11)
13518 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13519 } else {
13520 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13521 << DclT << Init->getSourceRange();
13522
13523 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13524 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13525 << Init->getSourceRange();
13526 VDecl->setInvalidDecl();
13527 }
13528 }
13529
13530 // Suggest adding 'constexpr' in C++11 for literal types.
13531 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13532 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13533 << DclT << Init->getSourceRange()
13534 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13535 VDecl->setConstexpr(true);
13536
13537 } else {
13538 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13539 << DclT << Init->getSourceRange();
13540 VDecl->setInvalidDecl();
13541 }
13542 } else if (VDecl->isFileVarDecl()) {
13543 // In C, extern is typically used to avoid tentative definitions when
13544 // declaring variables in headers, but adding an intializer makes it a
13545 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13546 // In C++, extern is often used to give implictly static const variables
13547 // external linkage, so don't warn in that case. If selectany is present,
13548 // this might be header code intended for C and C++ inclusion, so apply the
13549 // C++ rules.
13550 if (VDecl->getStorageClass() == SC_Extern &&
13551 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13553 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13555 Diag(VDecl->getLocation(), diag::warn_extern_init);
13556
13557 // In Microsoft C++ mode, a const variable defined in namespace scope has
13558 // external linkage by default if the variable is declared with
13559 // __declspec(dllexport).
13562 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13563 VDecl->setStorageClass(SC_Extern);
13564
13565 // C99 6.7.8p4. All file scoped initializers need to be constant.
13566 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13567 CheckForConstantInitializer(Init, DclT);
13568 }
13569
13570 QualType InitType = Init->getType();
13571 if (!InitType.isNull() &&
13574 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13575
13576 // We will represent direct-initialization similarly to copy-initialization:
13577 // int x(1); -as-> int x = 1;
13578 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13579 //
13580 // Clients that want to distinguish between the two forms, can check for
13581 // direct initializer using VarDecl::getInitStyle().
13582 // A major benefit is that clients that don't particularly care about which
13583 // exactly form was it (like the CodeGen) can handle both cases without
13584 // special case code.
13585
13586 // C++ 8.5p11:
13587 // The form of initialization (using parentheses or '=') is generally
13588 // insignificant, but does matter when the entity being initialized has a
13589 // class type.
13590 if (CXXDirectInit) {
13591 assert(DirectInit && "Call-style initializer must be direct init.");
13592 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13594 } else if (DirectInit) {
13595 // This must be list-initialization. No other way is direct-initialization.
13597 }
13598
13599 if (LangOpts.OpenMP &&
13600 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13601 VDecl->isFileVarDecl())
13602 DeclsToCheckForDeferredDiags.insert(VDecl);
13604}
13605
13606/// ActOnInitializerError - Given that there was an error parsing an
13607/// initializer for the given declaration, try to at least re-establish
13608/// invariants such as whether a variable's type is either dependent or
13609/// complete.
13611 // Our main concern here is re-establishing invariants like "a
13612 // variable's type is either dependent or complete".
13613 if (!D || D->isInvalidDecl()) return;
13614
13615 VarDecl *VD = dyn_cast<VarDecl>(D);
13616 if (!VD) return;
13617
13618 // Bindings are not usable if we can't make sense of the initializer.
13619 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13620 for (auto *BD : DD->bindings())
13621 BD->setInvalidDecl();
13622
13623 // Auto types are meaningless if we can't make sense of the initializer.
13624 if (VD->getType()->isUndeducedType()) {
13625 D->setInvalidDecl();
13626 return;
13627 }
13628
13629 QualType Ty = VD->getType();
13630 if (Ty->isDependentType()) return;
13631
13632 // Require a complete type.
13635 diag::err_typecheck_decl_incomplete_type)) {
13636 VD->setInvalidDecl();
13637 return;
13638 }
13639
13640 // Require a non-abstract type.
13641 if (RequireNonAbstractType(VD->getLocation(), Ty,
13642 diag::err_abstract_type_in_decl,
13644 VD->setInvalidDecl();
13645 return;
13646 }
13647
13648 // Don't bother complaining about constructors or destructors,
13649 // though.
13650}
13651
13653 // If there is no declaration, there was an error parsing it. Just ignore it.
13654 if (!RealDecl)
13655 return;
13656
13657 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13658 QualType Type = Var->getType();
13659
13660 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13661 if (isa<DecompositionDecl>(RealDecl)) {
13662 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13663 Var->setInvalidDecl();
13664 return;
13665 }
13666
13667 if (Type->isUndeducedType() &&
13668 DeduceVariableDeclarationType(Var, false, nullptr))
13669 return;
13670
13671 // C++11 [class.static.data]p3: A static data member can be declared with
13672 // the constexpr specifier; if so, its declaration shall specify
13673 // a brace-or-equal-initializer.
13674 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13675 // the definition of a variable [...] or the declaration of a static data
13676 // member.
13677 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13678 !Var->isThisDeclarationADemotedDefinition()) {
13679 if (Var->isStaticDataMember()) {
13680 // C++1z removes the relevant rule; the in-class declaration is always
13681 // a definition there.
13682 if (!getLangOpts().CPlusPlus17 &&
13684 Diag(Var->getLocation(),
13685 diag::err_constexpr_static_mem_var_requires_init)
13686 << Var;
13687 Var->setInvalidDecl();
13688 return;
13689 }
13690 } else {
13691 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13692 Var->setInvalidDecl();
13693 return;
13694 }
13695 }
13696
13697 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13698 // be initialized.
13699 if (!Var->isInvalidDecl() &&
13700 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13701 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13702 bool HasConstExprDefaultConstructor = false;
13703 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13704 for (auto *Ctor : RD->ctors()) {
13705 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13706 Ctor->getMethodQualifiers().getAddressSpace() ==
13708 HasConstExprDefaultConstructor = true;
13709 }
13710 }
13711 }
13712 if (!HasConstExprDefaultConstructor) {
13713 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13714 Var->setInvalidDecl();
13715 return;
13716 }
13717 }
13718
13719 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13720 if (Var->getStorageClass() == SC_Extern) {
13721 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13722 << Var;
13723 Var->setInvalidDecl();
13724 return;
13725 }
13726 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13727 diag::err_typecheck_decl_incomplete_type)) {
13728 Var->setInvalidDecl();
13729 return;
13730 }
13731 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13732 if (!RD->hasTrivialDefaultConstructor()) {
13733 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13734 Var->setInvalidDecl();
13735 return;
13736 }
13737 }
13738 // The declaration is unitialized, no need for further checks.
13739 return;
13740 }
13741
13742 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13743 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13744 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13745 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13747
13748
13749 switch (DefKind) {
13751 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13752 break;
13753
13754 // We have an out-of-line definition of a static data member
13755 // that has an in-class initializer, so we type-check this like
13756 // a declaration.
13757 //
13758 [[fallthrough]];
13759
13761 // It's only a declaration.
13762
13763 // Block scope. C99 6.7p7: If an identifier for an object is
13764 // declared with no linkage (C99 6.2.2p6), the type for the
13765 // object shall be complete.
13766 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13767 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13768 RequireCompleteType(Var->getLocation(), Type,
13769 diag::err_typecheck_decl_incomplete_type))
13770 Var->setInvalidDecl();
13771
13772 // Make sure that the type is not abstract.
13773 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13774 RequireNonAbstractType(Var->getLocation(), Type,
13775 diag::err_abstract_type_in_decl,
13777 Var->setInvalidDecl();
13778 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13779 Var->getStorageClass() == SC_PrivateExtern) {
13780 Diag(Var->getLocation(), diag::warn_private_extern);
13781 Diag(Var->getLocation(), diag::note_private_extern);
13782 }
13783
13785 !Var->isInvalidDecl())
13786 ExternalDeclarations.push_back(Var);
13787
13788 return;
13789
13791 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13792 // object that has file scope without an initializer, and without a
13793 // storage-class specifier or with the storage-class specifier "static",
13794 // constitutes a tentative definition. Note: A tentative definition with
13795 // external linkage is valid (C99 6.2.2p5).
13796 if (!Var->isInvalidDecl()) {
13797 if (const IncompleteArrayType *ArrayT
13800 Var->getLocation(), ArrayT->getElementType(),
13801 diag::err_array_incomplete_or_sizeless_type))
13802 Var->setInvalidDecl();
13803 } else if (Var->getStorageClass() == SC_Static) {
13804 // C99 6.9.2p3: If the declaration of an identifier for an object is
13805 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13806 // declared type shall not be an incomplete type.
13807 // NOTE: code such as the following
13808 // static struct s;
13809 // struct s { int a; };
13810 // is accepted by gcc. Hence here we issue a warning instead of
13811 // an error and we do not invalidate the static declaration.
13812 // NOTE: to avoid multiple warnings, only check the first declaration.
13813 if (Var->isFirstDecl())
13814 RequireCompleteType(Var->getLocation(), Type,
13815 diag::ext_typecheck_decl_incomplete_type);
13816 }
13817 }
13818
13819 // Record the tentative definition; we're done.
13820 if (!Var->isInvalidDecl())
13822 return;
13823 }
13824
13825 // Provide a specific diagnostic for uninitialized variable
13826 // definitions with incomplete array type.
13827 if (Type->isIncompleteArrayType()) {
13828 if (Var->isConstexpr())
13829 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13830 << Var;
13831 else
13832 Diag(Var->getLocation(),
13833 diag::err_typecheck_incomplete_array_needs_initializer);
13834 Var->setInvalidDecl();
13835 return;
13836 }
13837
13838 // Provide a specific diagnostic for uninitialized variable
13839 // definitions with reference type.
13840 if (Type->isReferenceType()) {
13841 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13842 << Var << SourceRange(Var->getLocation(), Var->getLocation());
13843 return;
13844 }
13845
13846 // Do not attempt to type-check the default initializer for a
13847 // variable with dependent type.
13848 if (Type->isDependentType())
13849 return;
13850
13851 if (Var->isInvalidDecl())
13852 return;
13853
13854 if (!Var->hasAttr<AliasAttr>()) {
13855 if (RequireCompleteType(Var->getLocation(),
13857 diag::err_typecheck_decl_incomplete_type)) {
13858 Var->setInvalidDecl();
13859 return;
13860 }
13861 } else {
13862 return;
13863 }
13864
13865 // The variable can not have an abstract class type.
13866 if (RequireNonAbstractType(Var->getLocation(), Type,
13867 diag::err_abstract_type_in_decl,
13869 Var->setInvalidDecl();
13870 return;
13871 }
13872
13873 // Check for jumps past the implicit initializer. C++0x
13874 // clarifies that this applies to a "variable with automatic
13875 // storage duration", not a "local variable".
13876 // C++11 [stmt.dcl]p3
13877 // A program that jumps from a point where a variable with automatic
13878 // storage duration is not in scope to a point where it is in scope is
13879 // ill-formed unless the variable has scalar type, class type with a
13880 // trivial default constructor and a trivial destructor, a cv-qualified
13881 // version of one of these types, or an array of one of the preceding
13882 // types and is declared without an initializer.
13883 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13884 if (const RecordType *Record
13885 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13886 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13887 // Mark the function (if we're in one) for further checking even if the
13888 // looser rules of C++11 do not require such checks, so that we can
13889 // diagnose incompatibilities with C++98.
13890 if (!CXXRecord->isPOD())
13892 }
13893 }
13894 // In OpenCL, we can't initialize objects in the __local address space,
13895 // even implicitly, so don't synthesize an implicit initializer.
13896 if (getLangOpts().OpenCL &&
13897 Var->getType().getAddressSpace() == LangAS::opencl_local)
13898 return;
13899 // C++03 [dcl.init]p9:
13900 // If no initializer is specified for an object, and the
13901 // object is of (possibly cv-qualified) non-POD class type (or
13902 // array thereof), the object shall be default-initialized; if
13903 // the object is of const-qualified type, the underlying class
13904 // type shall have a user-declared default
13905 // constructor. Otherwise, if no initializer is specified for
13906 // a non- static object, the object and its subobjects, if
13907 // any, have an indeterminate initial value); if the object
13908 // or any of its subobjects are of const-qualified type, the
13909 // program is ill-formed.
13910 // C++0x [dcl.init]p11:
13911 // If no initializer is specified for an object, the object is
13912 // default-initialized; [...].
13915 = InitializationKind::CreateDefault(Var->getLocation());
13916
13917 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
13918 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
13919
13920 if (Init.get()) {
13921 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13922 // This is important for template substitution.
13923 Var->setInitStyle(VarDecl::CallInit);
13924 } else if (Init.isInvalid()) {
13925 // If default-init fails, attach a recovery-expr initializer to track
13926 // that initialization was attempted and failed.
13927 auto RecoveryExpr =
13928 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13929 if (RecoveryExpr.get())
13930 Var->setInit(RecoveryExpr.get());
13931 }
13932
13934 }
13935}
13936
13938 // If there is no declaration, there was an error parsing it. Ignore it.
13939 if (!D)
13940 return;
13941
13942 VarDecl *VD = dyn_cast<VarDecl>(D);
13943 if (!VD) {
13944 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13945 D->setInvalidDecl();
13946 return;
13947 }
13948
13949 VD->setCXXForRangeDecl(true);
13950
13951 // for-range-declaration cannot be given a storage class specifier.
13952 int Error = -1;
13953 switch (VD->getStorageClass()) {
13954 case SC_None:
13955 break;
13956 case SC_Extern:
13957 Error = 0;
13958 break;
13959 case SC_Static:
13960 Error = 1;
13961 break;
13962 case SC_PrivateExtern:
13963 Error = 2;
13964 break;
13965 case SC_Auto:
13966 Error = 3;
13967 break;
13968 case SC_Register:
13969 Error = 4;
13970 break;
13971 }
13972
13973 // for-range-declaration cannot be given a storage class specifier con't.
13974 switch (VD->getTSCSpec()) {
13975 case TSCS_thread_local:
13976 Error = 6;
13977 break;
13978 case TSCS___thread:
13979 case TSCS__Thread_local:
13980 case TSCS_unspecified:
13981 break;
13982 }
13983
13984 if (Error != -1) {
13985 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13986 << VD << Error;
13987 D->setInvalidDecl();
13988 }
13989}
13990
13992 IdentifierInfo *Ident,
13993 ParsedAttributes &Attrs) {
13994 // C++1y [stmt.iter]p1:
13995 // A range-based for statement of the form
13996 // for ( for-range-identifier : for-range-initializer ) statement
13997 // is equivalent to
13998 // for ( auto&& for-range-identifier : for-range-initializer ) statement
13999 DeclSpec DS(Attrs.getPool().getFactory());
14000
14001 const char *PrevSpec;
14002 unsigned DiagID;
14003 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14005
14007 D.SetIdentifier(Ident, IdentLoc);
14008 D.takeAttributes(Attrs);
14009
14010 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14011 IdentLoc);
14012 Decl *Var = ActOnDeclarator(S, D);
14013 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14015 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14016 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14017 : IdentLoc);
14018}
14019
14021 if (var->isInvalidDecl()) return;
14022
14024
14025 if (getLangOpts().OpenCL) {
14026 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14027 // initialiser
14028 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14029 !var->hasInit()) {
14030 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14031 << 1 /*Init*/;
14032 var->setInvalidDecl();
14033 return;
14034 }
14035 }
14036
14037 // In Objective-C, don't allow jumps past the implicit initialization of a
14038 // local retaining variable.
14039 if (getLangOpts().ObjC &&
14040 var->hasLocalStorage()) {
14041 switch (var->getType().getObjCLifetime()) {
14045 break;
14046
14050 break;
14051 }
14052 }
14053
14054 if (var->hasLocalStorage() &&
14057
14058 // Warn about externally-visible variables being defined without a
14059 // prior declaration. We only want to do this for global
14060 // declarations, but we also specifically need to avoid doing it for
14061 // class members because the linkage of an anonymous class can
14062 // change if it's later given a typedef name.
14063 if (var->isThisDeclarationADefinition() &&
14065 var->isExternallyVisible() && var->hasLinkage() &&
14066 !var->isInline() && !var->getDescribedVarTemplate() &&
14067 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14069 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14070 var->getLocation())) {
14071 // Find a previous declaration that's not a definition.
14072 VarDecl *prev = var->getPreviousDecl();
14073 while (prev && prev->isThisDeclarationADefinition())
14074 prev = prev->getPreviousDecl();
14075
14076 if (!prev) {
14077 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14078 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14079 << /* variable */ 0;
14080 }
14081 }
14082
14083 // Cache the result of checking for constant initialization.
14084 std::optional<bool> CacheHasConstInit;
14085 const Expr *CacheCulprit = nullptr;
14086 auto checkConstInit = [&]() mutable {
14087 if (!CacheHasConstInit)
14088 CacheHasConstInit = var->getInit()->isConstantInitializer(
14089 Context, var->getType()->isReferenceType(), &CacheCulprit);
14090 return *CacheHasConstInit;
14091 };
14092
14093 if (var->getTLSKind() == VarDecl::TLS_Static) {
14094 if (var->getType().isDestructedType()) {
14095 // GNU C++98 edits for __thread, [basic.start.term]p3:
14096 // The type of an object with thread storage duration shall not
14097 // have a non-trivial destructor.
14098 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14100 Diag(var->getLocation(), diag::note_use_thread_local);
14101 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14102 if (!checkConstInit()) {
14103 // GNU C++98 edits for __thread, [basic.start.init]p4:
14104 // An object of thread storage duration shall not require dynamic
14105 // initialization.
14106 // FIXME: Need strict checking here.
14107 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14108 << CacheCulprit->getSourceRange();
14110 Diag(var->getLocation(), diag::note_use_thread_local);
14111 }
14112 }
14113 }
14114
14115
14116 if (!var->getType()->isStructureType() && var->hasInit() &&
14117 isa<InitListExpr>(var->getInit())) {
14118 const auto *ILE = cast<InitListExpr>(var->getInit());
14119 unsigned NumInits = ILE->getNumInits();
14120 if (NumInits > 2)
14121 for (unsigned I = 0; I < NumInits; ++I) {
14122 const auto *Init = ILE->getInit(I);
14123 if (!Init)
14124 break;
14125 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14126 if (!SL)
14127 break;
14128
14129 unsigned NumConcat = SL->getNumConcatenated();
14130 // Diagnose missing comma in string array initialization.
14131 // Do not warn when all the elements in the initializer are concatenated
14132 // together. Do not warn for macros too.
14133 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14134 bool OnlyOneMissingComma = true;
14135 for (unsigned J = I + 1; J < NumInits; ++J) {
14136 const auto *Init = ILE->getInit(J);
14137 if (!Init)
14138 break;
14139 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14140 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14141 OnlyOneMissingComma = false;
14142 break;
14143 }
14144 }
14145
14146 if (OnlyOneMissingComma) {
14148 for (unsigned i = 0; i < NumConcat - 1; ++i)
14149 Hints.push_back(FixItHint::CreateInsertion(
14150 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14151
14152 Diag(SL->getStrTokenLoc(1),
14153 diag::warn_concatenated_literal_array_init)
14154 << Hints;
14155 Diag(SL->getBeginLoc(),
14156 diag::note_concatenated_string_literal_silence);
14157 }
14158 // In any case, stop now.
14159 break;
14160 }
14161 }
14162 }
14163
14164
14165 QualType type = var->getType();
14166
14167 if (var->hasAttr<BlocksAttr>())
14169
14170 Expr *Init = var->getInit();
14171 bool GlobalStorage = var->hasGlobalStorage();
14172 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14173 QualType baseType = Context.getBaseElementType(type);
14174 bool HasConstInit = true;
14175
14176 // Check whether the initializer is sufficiently constant.
14177 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14178 !Init->isValueDependent() &&
14179 (GlobalStorage || var->isConstexpr() ||
14181 // If this variable might have a constant initializer or might be usable in
14182 // constant expressions, check whether or not it actually is now. We can't
14183 // do this lazily, because the result might depend on things that change
14184 // later, such as which constexpr functions happen to be defined.
14186 if (!getLangOpts().CPlusPlus11) {
14187 // Prior to C++11, in contexts where a constant initializer is required,
14188 // the set of valid constant initializers is described by syntactic rules
14189 // in [expr.const]p2-6.
14190 // FIXME: Stricter checking for these rules would be useful for constinit /
14191 // -Wglobal-constructors.
14192 HasConstInit = checkConstInit();
14193
14194 // Compute and cache the constant value, and remember that we have a
14195 // constant initializer.
14196 if (HasConstInit) {
14197 (void)var->checkForConstantInitialization(Notes);
14198 Notes.clear();
14199 } else if (CacheCulprit) {
14200 Notes.emplace_back(CacheCulprit->getExprLoc(),
14201 PDiag(diag::note_invalid_subexpr_in_const_expr));
14202 Notes.back().second << CacheCulprit->getSourceRange();
14203 }
14204 } else {
14205 // Evaluate the initializer to see if it's a constant initializer.
14206 HasConstInit = var->checkForConstantInitialization(Notes);
14207 }
14208
14209 if (HasConstInit) {
14210 // FIXME: Consider replacing the initializer with a ConstantExpr.
14211 } else if (var->isConstexpr()) {
14212 SourceLocation DiagLoc = var->getLocation();
14213 // If the note doesn't add any useful information other than a source
14214 // location, fold it into the primary diagnostic.
14215 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14216 diag::note_invalid_subexpr_in_const_expr) {
14217 DiagLoc = Notes[0].first;
14218 Notes.clear();
14219 }
14220 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14221 << var << Init->getSourceRange();
14222 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14223 Diag(Notes[I].first, Notes[I].second);
14224 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14225 auto *Attr = var->getAttr<ConstInitAttr>();
14226 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14227 << Init->getSourceRange();
14228 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14229 << Attr->getRange() << Attr->isConstinit();
14230 for (auto &it : Notes)
14231 Diag(it.first, it.second);
14232 } else if (IsGlobal &&
14233 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14234 var->getLocation())) {
14235 // Warn about globals which don't have a constant initializer. Don't
14236 // warn about globals with a non-trivial destructor because we already
14237 // warned about them.
14238 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14239 if (!(RD && !RD->hasTrivialDestructor())) {
14240 // checkConstInit() here permits trivial default initialization even in
14241 // C++11 onwards, where such an initializer is not a constant initializer
14242 // but nonetheless doesn't require a global constructor.
14243 if (!checkConstInit())
14244 Diag(var->getLocation(), diag::warn_global_constructor)
14245 << Init->getSourceRange();
14246 }
14247 }
14248 }
14249
14250 // Apply section attributes and pragmas to global variables.
14251 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14253 PragmaStack<StringLiteral *> *Stack = nullptr;
14254 int SectionFlags = ASTContext::PSF_Read;
14255 if (var->getType().isConstQualified()) {
14256 if (HasConstInit)
14257 Stack = &ConstSegStack;
14258 else {
14259 Stack = &BSSSegStack;
14260 SectionFlags |= ASTContext::PSF_Write;
14261 }
14262 } else if (var->hasInit() && HasConstInit) {
14263 Stack = &DataSegStack;
14264 SectionFlags |= ASTContext::PSF_Write;
14265 } else {
14266 Stack = &BSSSegStack;
14267 SectionFlags |= ASTContext::PSF_Write;
14268 }
14269 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14270 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14271 SectionFlags |= ASTContext::PSF_Implicit;
14272 UnifySection(SA->getName(), SectionFlags, var);
14273 } else if (Stack->CurrentValue) {
14274 SectionFlags |= ASTContext::PSF_Implicit;
14275 auto SectionName = Stack->CurrentValue->getString();
14276 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14277 Stack->CurrentPragmaLocation,
14278 SectionAttr::Declspec_allocate));
14279 if (UnifySection(SectionName, SectionFlags, var))
14280 var->dropAttr<SectionAttr>();
14281 }
14282
14283 // Apply the init_seg attribute if this has an initializer. If the
14284 // initializer turns out to not be dynamic, we'll end up ignoring this
14285 // attribute.
14286 if (CurInitSeg && var->getInit())
14287 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14288 CurInitSegLoc));
14289 }
14290
14291 // All the following checks are C++ only.
14292 if (!getLangOpts().CPlusPlus) {
14293 // If this variable must be emitted, add it as an initializer for the
14294 // current module.
14295 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14296 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14297 return;
14298 }
14299
14300 // Require the destructor.
14301 if (!type->isDependentType())
14302 if (const RecordType *recordType = baseType->getAs<RecordType>())
14304
14305 // If this variable must be emitted, add it as an initializer for the current
14306 // module.
14307 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14308 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14309
14310 // Build the bindings if this is a structured binding declaration.
14311 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14313}
14314
14315/// Check if VD needs to be dllexport/dllimport due to being in a
14316/// dllexport/import function.
14318 assert(VD->isStaticLocal());
14319
14320 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14321
14322 // Find outermost function when VD is in lambda function.
14323 while (FD && !getDLLAttr(FD) &&
14324 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14325 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14326 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14327 }
14328
14329 if (!FD)
14330 return;
14331
14332 // Static locals inherit dll attributes from their function.
14333 if (Attr *A = getDLLAttr(FD)) {
14334 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14335 NewAttr->setInherited(true);
14336 VD->addAttr(NewAttr);
14337 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14338 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14339 NewAttr->setInherited(true);
14340 VD->addAttr(NewAttr);
14341
14342 // Export this function to enforce exporting this static variable even
14343 // if it is not used in this compilation unit.
14344 if (!FD->hasAttr<DLLExportAttr>())
14345 FD->addAttr(NewAttr);
14346
14347 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14348 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14349 NewAttr->setInherited(true);
14350 VD->addAttr(NewAttr);
14351 }
14352}
14353
14355 assert(VD->getTLSKind());
14356
14357 // Perform TLS alignment check here after attributes attached to the variable
14358 // which may affect the alignment have been processed. Only perform the check
14359 // if the target has a maximum TLS alignment (zero means no constraints).
14360 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14361 // Protect the check so that it's not performed on dependent types and
14362 // dependent alignments (we can't determine the alignment in that case).
14363 if (!VD->hasDependentAlignment()) {
14364 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14365 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14366 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14368 << (unsigned)MaxAlignChars.getQuantity();
14369 }
14370 }
14371 }
14372}
14373
14374/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14375/// any semantic actions necessary after any initializer has been attached.
14377 // Note that we are no longer parsing the initializer for this declaration.
14378 ParsingInitForAutoVars.erase(ThisDecl);
14379
14380 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14381 if (!VD)
14382 return;
14383
14384 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14386 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14388 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14392 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14396 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14400 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14403 }
14404
14405 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14406 for (auto *BD : DD->bindings()) {
14408 }
14409 }
14410
14411 checkAttributesAfterMerging(*this, *VD);
14412
14413 if (VD->isStaticLocal())
14415
14416 if (VD->getTLSKind())
14418
14419 // Perform check for initializers of device-side global variables.
14420 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14421 // 7.5). We must also apply the same checks to all __shared__
14422 // variables whether they are local or not. CUDA also allows
14423 // constant initializers for __constant__ and __device__ variables.
14424 if (getLangOpts().CUDA)
14426
14427 // Grab the dllimport or dllexport attribute off of the VarDecl.
14428 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14429
14430 // Imported static data members cannot be defined out-of-line.
14431 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14432 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14434 // We allow definitions of dllimport class template static data members
14435 // with a warning.
14438 bool IsClassTemplateMember =
14440 Context->getDescribedClassTemplate();
14441
14442 Diag(VD->getLocation(),
14443 IsClassTemplateMember
14444 ? diag::warn_attribute_dllimport_static_field_definition
14445 : diag::err_attribute_dllimport_static_field_definition);
14446 Diag(IA->getLocation(), diag::note_attribute);
14447 if (!IsClassTemplateMember)
14448 VD->setInvalidDecl();
14449 }
14450 }
14451
14452 // dllimport/dllexport variables cannot be thread local, their TLS index
14453 // isn't exported with the variable.
14454 if (DLLAttr && VD->getTLSKind()) {
14455 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14456 if (F && getDLLAttr(F)) {
14457 assert(VD->isStaticLocal());
14458 // But if this is a static local in a dlimport/dllexport function, the
14459 // function will never be inlined, which means the var would never be
14460 // imported, so having it marked import/export is safe.
14461 } else {
14462 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14463 << DLLAttr;
14464 VD->setInvalidDecl();
14465 }
14466 }
14467
14468 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14469 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14470 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14471 << Attr;
14472 VD->dropAttr<UsedAttr>();
14473 }
14474 }
14475 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14476 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14477 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14478 << Attr;
14479 VD->dropAttr<RetainAttr>();
14480 }
14481 }
14482
14483 const DeclContext *DC = VD->getDeclContext();
14484 // If there's a #pragma GCC visibility in scope, and this isn't a class
14485 // member, set the visibility of this variable.
14488
14489 // FIXME: Warn on unused var template partial specializations.
14490 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14492
14493 // Now we have parsed the initializer and can update the table of magic
14494 // tag values.
14495 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14497 return;
14498
14499 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14500 const Expr *MagicValueExpr = VD->getInit();
14501 if (!MagicValueExpr) {
14502 continue;
14503 }
14504 std::optional<llvm::APSInt> MagicValueInt;
14505 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14506 Diag(I->getRange().getBegin(),
14507 diag::err_type_tag_for_datatype_not_ice)
14508 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14509 continue;
14510 }
14511 if (MagicValueInt->getActiveBits() > 64) {
14512 Diag(I->getRange().getBegin(),
14513 diag::err_type_tag_for_datatype_too_large)
14514 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14515 continue;
14516 }
14517 uint64_t MagicValue = MagicValueInt->getZExtValue();
14518 RegisterTypeTagForDatatype(I->getArgumentKind(),
14519 MagicValue,
14520 I->getMatchingCType(),
14521 I->getLayoutCompatible(),
14522 I->getMustBeNull());
14523 }
14524}
14525
14527 auto *VD = dyn_cast<VarDecl>(DD);
14528 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14529}
14530
14532 ArrayRef<Decl *> Group) {
14534
14535 if (DS.isTypeSpecOwned())
14536 Decls.push_back(DS.getRepAsDecl());
14537
14538 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14539 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14540 bool DiagnosedMultipleDecomps = false;
14541 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14542 bool DiagnosedNonDeducedAuto = false;
14543
14544 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14545 if (Decl *D = Group[i]) {
14546 // Check if the Decl has been declared in '#pragma omp declare target'
14547 // directive and has static storage duration.
14548 if (auto *VD = dyn_cast<VarDecl>(D);
14549 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14550 VD->hasGlobalStorage())
14552 // For declarators, there are some additional syntactic-ish checks we need
14553 // to perform.
14554 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14555 if (!FirstDeclaratorInGroup)
14556 FirstDeclaratorInGroup = DD;
14557 if (!FirstDecompDeclaratorInGroup)
14558 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14559 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14560 !hasDeducedAuto(DD))
14561 FirstNonDeducedAutoInGroup = DD;
14562
14563 if (FirstDeclaratorInGroup != DD) {
14564 // A decomposition declaration cannot be combined with any other
14565 // declaration in the same group.
14566 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14567 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14568 diag::err_decomp_decl_not_alone)
14569 << FirstDeclaratorInGroup->getSourceRange()
14570 << DD->getSourceRange();
14571 DiagnosedMultipleDecomps = true;
14572 }
14573
14574 // A declarator that uses 'auto' in any way other than to declare a
14575 // variable with a deduced type cannot be combined with any other
14576 // declarator in the same group.
14577 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14578 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14579 diag::err_auto_non_deduced_not_alone)
14580 << FirstNonDeducedAutoInGroup->getType()
14582 << FirstDeclaratorInGroup->getSourceRange()
14583 << DD->getSourceRange();
14584 DiagnosedNonDeducedAuto = true;
14585 }
14586 }
14587 }
14588
14589 Decls.push_back(D);
14590 }
14591 }
14592
14594 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14595 handleTagNumbering(Tag, S);
14596 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14598 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14599 }
14600 }
14601
14602 return BuildDeclaratorGroup(Decls);
14603}
14604
14605/// BuildDeclaratorGroup - convert a list of declarations into a declaration
14606/// group, performing any necessary semantic checking.
14609 // C++14 [dcl.spec.auto]p7: (DR1347)
14610 // If the type that replaces the placeholder type is not the same in each
14611 // deduction, the program is ill-formed.
14612 if (Group.size() > 1) {
14613 QualType Deduced;
14614 VarDecl *DeducedDecl = nullptr;
14615 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14616 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14617 if (!D || D->isInvalidDecl())
14618 break;
14619 DeducedType *DT = D->getType()->getContainedDeducedType();
14620 if (!DT || DT->getDeducedType().isNull())
14621 continue;
14622 if (Deduced.isNull()) {
14623 Deduced = DT->getDeducedType();
14624 DeducedDecl = D;
14625 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14626 auto *AT = dyn_cast<AutoType>(DT);
14627 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14628 diag::err_auto_different_deductions)
14629 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14630 << DeducedDecl->getDeclName() << DT->getDeducedType()
14631 << D->getDeclName();
14632 if (DeducedDecl->hasInit())
14633 Dia << DeducedDecl->getInit()->getSourceRange();
14634 if (D->getInit())
14635 Dia << D->getInit()->getSourceRange();
14636 D->setInvalidDecl();
14637 break;
14638 }
14639 }
14640 }
14641
14643
14644 return DeclGroupPtrTy::make(
14645 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14646}
14647
14651
14653 // Don't parse the comment if Doxygen diagnostics are ignored.
14654 if (Group.empty() || !Group[0])
14655 return;
14656
14657 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14658 Group[0]->getLocation()) &&
14659 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14660 Group[0]->getLocation()))
14661 return;
14662
14663 if (Group.size() >= 2) {
14664 // This is a decl group. Normally it will contain only declarations
14665 // produced from declarator list. But in case we have any definitions or
14666 // additional declaration references:
14667 // 'typedef struct S {} S;'
14668 // 'typedef struct S *S;'
14669 // 'struct S *pS;'
14670 // FinalizeDeclaratorGroup adds these as separate declarations.
14671 Decl *MaybeTagDecl = Group[0];
14672 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14673 Group = Group.slice(1);
14674 }
14675 }
14676
14677 // FIMXE: We assume every Decl in the group is in the same file.
14678 // This is false when preprocessor constructs the group from decls in
14679 // different files (e. g. macros or #include).
14681}
14682
14683/// Common checks for a parameter-declaration that should apply to both function
14684/// parameters and non-type template parameters.
14686 // Check that there are no default arguments inside the type of this
14687 // parameter.
14688 if (getLangOpts().CPlusPlus)
14690
14691 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14692 if (D.getCXXScopeSpec().isSet()) {
14693 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14694 << D.getCXXScopeSpec().getRange();
14695 }
14696
14697 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14698 // simple identifier except [...irrelevant cases...].
14699 switch (D.getName().getKind()) {
14701 break;
14702
14710 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14712 break;
14713
14716 // GetNameForDeclarator would not produce a useful name in this case.
14717 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14718 break;
14719 }
14720}
14721
14722/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
14723/// to introduce parameters into function prototype scope.
14725 const DeclSpec &DS = D.getDeclSpec();
14726
14727 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14728
14729 // C++03 [dcl.stc]p2 also permits 'auto'.
14730 StorageClass SC = SC_None;
14732 SC = SC_Register;
14733 // In C++11, the 'register' storage class specifier is deprecated.
14734 // In C++17, it is not allowed, but we tolerate it as an extension.
14735 if (getLangOpts().CPlusPlus11) {
14737 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14738 : diag::warn_deprecated_register)
14740 }
14741 } else if (getLangOpts().CPlusPlus &&
14743 SC = SC_Auto;
14746 diag::err_invalid_storage_class_in_func_decl);
14748 }
14749
14751 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14753 if (DS.isInlineSpecified())
14754 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14755 << getLangOpts().CPlusPlus17;
14756 if (DS.hasConstexprSpecifier())
14757 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14758 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14759
14761
14763
14764 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14765 QualType parmDeclType = TInfo->getType();
14766
14767 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14768 IdentifierInfo *II = D.getIdentifier();
14769 if (II) {
14772 LookupName(R, S);
14773 if (R.isSingleResult()) {
14774 NamedDecl *PrevDecl = R.getFoundDecl();
14775 if (PrevDecl->isTemplateParameter()) {
14776 // Maybe we will complain about the shadowed template parameter.
14778 // Just pretend that we didn't see the previous declaration.
14779 PrevDecl = nullptr;
14780 } else if (S->isDeclScope(PrevDecl)) {
14781 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14782 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14783
14784 // Recover by removing the name
14785 II = nullptr;
14786 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14787 D.setInvalidType(true);
14788 }
14789 }
14790 }
14791
14792 // Temporarily put parameter variables in the translation unit, not
14793 // the enclosing context. This prevents them from accidentally
14794 // looking like class members in C++.
14795 ParmVarDecl *New =
14797 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14798
14799 if (D.isInvalidType())
14800 New->setInvalidDecl();
14801
14802 assert(S->isFunctionPrototypeScope());
14803 assert(S->getFunctionPrototypeDepth() >= 1);
14804 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14805 S->getNextFunctionPrototypeIndex());
14806
14807 // Add the parameter declaration into this scope.
14808 S->AddDecl(New);
14809 if (II)
14810 IdResolver.AddDecl(New);
14811
14812 ProcessDeclAttributes(S, New, D);
14813
14815 Diag(New->getLocation(), diag::err_module_private_local)
14816 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14818
14819 if (New->hasAttr<BlocksAttr>()) {
14820 Diag(New->getLocation(), diag::err_block_on_nonlocal);
14821 }
14822
14823 if (getLangOpts().OpenCL)
14825
14826 return New;
14827}
14828
14829/// Synthesizes a variable for a parameter arising from a
14830/// typedef.
14832 SourceLocation Loc,
14833 QualType T) {
14834 /* FIXME: setting StartLoc == Loc.
14835 Would it be worth to modify callers so as to provide proper source
14836 location for the unnamed parameters, embedding the parameter's type? */
14837 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14839 SC_None, nullptr);
14840 Param->setImplicit();
14841 return Param;
14842}
14843
14845 // Don't diagnose unused-parameter errors in template instantiations; we
14846 // will already have done so in the template itself.
14848 return;
14849
14850 for (const ParmVarDecl *Parameter : Parameters) {
14851 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14852 !Parameter->hasAttr<UnusedAttr>()) {
14853 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14854 << Parameter->getDeclName();
14855 }
14856 }
14857}
14858
14860 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14861 if (LangOpts.NumLargeByValueCopy == 0) // No check.
14862 return;
14863
14864 // Warn if the return value is pass-by-value and larger than the specified
14865 // threshold.
14866 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14867 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14868 if (Size > LangOpts.NumLargeByValueCopy)
14869 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14870 }
14871
14872 // Warn if any parameter is pass-by-value and larger than the specified
14873 // threshold.
14874 for (const ParmVarDecl *Parameter : Parameters) {
14875 QualType T = Parameter->getType();
14876 if (T->isDependentType() || !T.isPODType(Context))
14877 continue;
14878 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14879 if (Size > LangOpts.NumLargeByValueCopy)
14880 Diag(Parameter->getLocation(), diag::warn_parameter_size)
14881 << Parameter << Size;
14882 }
14883}
14884
14886 SourceLocation NameLoc, IdentifierInfo *Name,
14887 QualType T, TypeSourceInfo *TSInfo,
14888 StorageClass SC) {
14889 // In ARC, infer a lifetime qualifier for appropriate parameter types.
14890 if (getLangOpts().ObjCAutoRefCount &&
14891 T.getObjCLifetime() == Qualifiers::OCL_None &&
14892 T->isObjCLifetimeType()) {
14893
14894 Qualifiers::ObjCLifetime lifetime;
14895
14896 // Special cases for arrays:
14897 // - if it's const, use __unsafe_unretained
14898 // - otherwise, it's an error
14899 if (T->isArrayType()) {
14900 if (!T.isConstQualified()) {
14904 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14905 else
14906 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14907 << TSInfo->getTypeLoc().getSourceRange();
14908 }
14910 } else {
14911 lifetime = T->getObjCARCImplicitLifetime();
14912 }
14913 T = Context.getLifetimeQualifiedType(T, lifetime);
14914 }
14915
14916 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14918 TSInfo, SC, nullptr);
14919
14920 // Make a note if we created a new pack in the scope of a lambda, so that
14921 // we know that references to that pack must also be expanded within the
14922 // lambda scope.
14923 if (New->isParameterPack())
14924 if (auto *LSI = getEnclosingLambda())
14925 LSI->LocalPacks.push_back(New);
14926
14931
14932 // Parameter declarators cannot be interface types. All ObjC objects are
14933 // passed by reference.
14934 if (T->isObjCObjectType()) {
14935 SourceLocation TypeEndLoc =
14937 Diag(NameLoc,
14938 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14939 << FixItHint::CreateInsertion(TypeEndLoc, "*");
14941 New->setType(T);
14942 }
14943
14944 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14945 // duration shall not be qualified by an address-space qualifier."
14946 // Since all parameters have automatic store duration, they can not have
14947 // an address space.
14948 if (T.getAddressSpace() != LangAS::Default &&
14949 // OpenCL allows function arguments declared to be an array of a type
14950 // to be qualified with an address space.
14951 !(getLangOpts().OpenCL &&
14952 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
14953 // WebAssembly allows reference types as parameters. Funcref in particular
14954 // lives in a different address space.
14955 !(T->isFunctionPointerType() &&
14956 T.getAddressSpace() == LangAS::wasm_funcref)) {
14957 Diag(NameLoc, diag::err_arg_with_address_space);
14958 New->setInvalidDecl();
14959 }
14960
14961 // PPC MMA non-pointer types are not allowed as function argument types.
14962 if (Context.getTargetInfo().getTriple().isPPC64() &&
14963 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14964 New->setInvalidDecl();
14965 }
14966
14967 return New;
14968}
14969
14971 SourceLocation LocAfterDecls) {
14973
14974 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
14975 // in the declaration list shall have at least one declarator, those
14976 // declarators shall only declare identifiers from the identifier list, and
14977 // every identifier in the identifier list shall be declared.
14978 //
14979 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
14980 // identifiers it names shall be declared in the declaration list."
14981 //
14982 // This is why we only diagnose in C99 and later. Note, the other conditions
14983 // listed are checked elsewhere.
14984 if (!FTI.hasPrototype) {
14985 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14986 --i;
14987 if (FTI.Params[i].Param == nullptr) {
14988 if (getLangOpts().C99) {
14989 SmallString<256> Code;
14990 llvm::raw_svector_ostream(Code)
14991 << " int " << FTI.Params[i].Ident->getName() << ";\n";
14992 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14993 << FTI.Params[i].Ident
14994 << FixItHint::CreateInsertion(LocAfterDecls, Code);
14995 }
14996
14997 // Implicitly declare the argument as type 'int' for lack of a better
14998 // type.
14999 AttributeFactory attrs;
15000 DeclSpec DS(attrs);
15001 const char* PrevSpec; // unused
15002 unsigned DiagID; // unused
15003 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15004 DiagID, Context.getPrintingPolicy());
15005 // Use the identifier location for the type source range.
15006 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15007 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15010 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15011 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15012 }
15013 }
15014 }
15015}
15016
15017Decl *
15019 MultiTemplateParamsArg TemplateParameterLists,
15020 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15021 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15022 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15023 Scope *ParentScope = FnBodyScope->getParent();
15024
15025 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15026 // we define a non-templated function definition, we will create a declaration
15027 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15028 // The base function declaration will have the equivalent of an `omp declare
15029 // variant` annotation which specifies the mangled definition as a
15030 // specialization function under the OpenMP context defined as part of the
15031 // `omp begin declare variant`.
15035 ParentScope, D, TemplateParameterLists, Bases);
15036
15038 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15039 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15040
15041 if (!Bases.empty())
15043
15044 return Dcl;
15045}
15046
15050
15052 const FunctionDecl *&PossiblePrototype) {
15053 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15054 Prev = Prev->getPreviousDecl()) {
15055 // Ignore any declarations that occur in function or method
15056 // scope, because they aren't visible from the header.
15057 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15058 continue;
15059
15060 PossiblePrototype = Prev;
15061 return Prev->getType()->isFunctionProtoType();
15062 }
15063 return false;
15064}
15065
15066static bool
15068 const FunctionDecl *&PossiblePrototype) {
15069 // Don't warn about invalid declarations.
15070 if (FD->isInvalidDecl())
15071 return false;
15072
15073 // Or declarations that aren't global.
15074 if (!FD->isGlobal())
15075 return false;
15076
15077 // Don't warn about C++ member functions.
15078 if (isa<CXXMethodDecl>(FD))
15079 return false;
15080
15081 // Don't warn about 'main'.
15082 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15083 if (IdentifierInfo *II = FD->getIdentifier())
15084 if (II->isStr("main") || II->isStr("efi_main"))
15085 return false;
15086
15087 // Don't warn about inline functions.
15088 if (FD->isInlined())
15089 return false;
15090
15091 // Don't warn about function templates.
15093 return false;
15094
15095 // Don't warn about function template specializations.
15097 return false;
15098
15099 // Don't warn for OpenCL kernels.
15100 if (FD->hasAttr<OpenCLKernelAttr>())
15101 return false;
15102
15103 // Don't warn on explicitly deleted functions.
15104 if (FD->isDeleted())
15105 return false;
15106
15107 // Don't warn on implicitly local functions (such as having local-typed
15108 // parameters).
15109 if (!FD->isExternallyVisible())
15110 return false;
15111
15112 // If we were able to find a potential prototype, don't warn.
15113 if (FindPossiblePrototype(FD, PossiblePrototype))
15114 return false;
15115
15116 return true;
15117}
15118
15119void
15121 const FunctionDecl *EffectiveDefinition,
15122 SkipBodyInfo *SkipBody) {
15123 const FunctionDecl *Definition = EffectiveDefinition;
15124 if (!Definition &&
15125 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15126 return;
15127
15128 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15130 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15131 // A merged copy of the same function, instantiated as a member of
15132 // the same class, is OK.
15133 if (declaresSameEntity(OrigFD, OrigDef) &&
15134 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15135 cast<Decl>(FD->getLexicalDeclContext())))
15136 return;
15137 }
15138 }
15139 }
15140
15142 return;
15143
15144 // Don't emit an error when this is redefinition of a typo-corrected
15145 // definition.
15147 return;
15148
15149 // If we don't have a visible definition of the function, and it's inline or
15150 // a template, skip the new definition.
15151 if (SkipBody && !hasVisibleDefinition(Definition) &&
15152 (Definition->getFormalLinkage() == InternalLinkage ||
15153 Definition->isInlined() ||
15154 Definition->getDescribedFunctionTemplate() ||
15155 Definition->getNumTemplateParameterLists())) {
15156 SkipBody->ShouldSkip = true;
15157 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15158 if (auto *TD = Definition->getDescribedFunctionTemplate())
15161 return;
15162 }
15163
15164 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15165 Definition->getStorageClass() == SC_Extern)
15166 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15167 << FD << getLangOpts().CPlusPlus;
15168 else
15169 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15170
15171 Diag(Definition->getLocation(), diag::note_previous_definition);
15172 FD->setInvalidDecl();
15173}
15174
15175static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
15176 Sema &S) {
15177 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
15178
15180 LSI->CallOperator = CallOperator;
15181 LSI->Lambda = LambdaClass;
15182 LSI->ReturnType = CallOperator->getReturnType();
15183 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15184
15185 if (LCD == LCD_None)
15187 else if (LCD == LCD_ByCopy)
15189 else if (LCD == LCD_ByRef)
15191 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15192
15194 LSI->Mutable = !CallOperator->isConst();
15195
15196 // Add the captures to the LSI so they can be noted as already
15197 // captured within tryCaptureVar.
15198 auto I = LambdaClass->field_begin();
15199 for (const auto &C : LambdaClass->captures()) {
15200 if (C.capturesVariable()) {
15201 ValueDecl *VD = C.getCapturedVar();
15202 if (VD->isInitCapture())
15204 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15205 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15206 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15207 /*EllipsisLoc*/C.isPackExpansion()
15208 ? C.getEllipsisLoc() : SourceLocation(),
15209 I->getType(), /*Invalid*/false);
15210
15211 } else if (C.capturesThis()) {
15212 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15213 C.getCaptureKind() == LCK_StarThis);
15214 } else {
15215 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15216 I->getType());
15217 }
15218 ++I;
15219 }
15220}
15221
15223 SkipBodyInfo *SkipBody,
15224 FnBodyKind BodyKind) {
15225 if (!D) {
15226 // Parsing the function declaration failed in some way. Push on a fake scope
15227 // anyway so we can try to parse the function body.
15230 return D;
15231 }
15232
15233 FunctionDecl *FD = nullptr;
15234
15235 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15236 FD = FunTmpl->getTemplatedDecl();
15237 else
15238 FD = cast<FunctionDecl>(D);
15239
15240 // Do not push if it is a lambda because one is already pushed when building
15241 // the lambda in ActOnStartOfLambdaDefinition().
15242 if (!isLambdaCallOperator(FD))
15243 // [expr.const]/p14.1
15244 // An expression or conversion is in an immediate function context if it is
15245 // potentially evaluated and either: its innermost enclosing non-block scope
15246 // is a function parameter scope of an immediate function.
15249 : ExprEvalContexts.back().Context);
15250
15251 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15252 // context is nested in an immediate function context, so smaller contexts
15253 // that appear inside immediate functions (like variable initializers) are
15254 // considered to be inside an immediate function context even though by
15255 // themselves they are not immediate function contexts. But when a new
15256 // function is entered, we need to reset this tracking, since the entered
15257 // function might be not an immediate function.
15258 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15259 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15260 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15261
15262 // Check for defining attributes before the check for redefinition.
15263 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15264 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15265 FD->dropAttr<AliasAttr>();
15266 FD->setInvalidDecl();
15267 }
15268 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15269 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15270 FD->dropAttr<IFuncAttr>();
15271 FD->setInvalidDecl();
15272 }
15273 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15274 if (!Context.getTargetInfo().hasFeature("fmv") &&
15275 !Attr->isDefaultVersion()) {
15276 // If function multi versioning disabled skip parsing function body
15277 // defined with non-default target_version attribute
15278 if (SkipBody)
15279 SkipBody->ShouldSkip = true;
15280 return nullptr;
15281 }
15282 }
15283
15284 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15285 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15286 Ctor->isDefaultConstructor() &&
15288 // If this is an MS ABI dllexport default constructor, instantiate any
15289 // default arguments.
15291 }
15292 }
15293
15294 // See if this is a redefinition. If 'will have body' (or similar) is already
15295 // set, then these checks were already performed when it was set.
15296 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15298 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15299
15300 // If we're skipping the body, we're done. Don't enter the scope.
15301 if (SkipBody && SkipBody->ShouldSkip)
15302 return D;
15303 }
15304
15305 // Mark this function as "will have a body eventually". This lets users to
15306 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15307 // this function.
15308 FD->setWillHaveBody();
15309
15310 // If we are instantiating a generic lambda call operator, push
15311 // a LambdaScopeInfo onto the function stack. But use the information
15312 // that's already been calculated (ActOnLambdaExpr) to prime the current
15313 // LambdaScopeInfo.
15314 // When the template operator is being specialized, the LambdaScopeInfo,
15315 // has to be properly restored so that tryCaptureVariable doesn't try
15316 // and capture any new variables. In addition when calculating potential
15317 // captures during transformation of nested lambdas, it is necessary to
15318 // have the LSI properly restored.
15320 assert(inTemplateInstantiation() &&
15321 "There should be an active template instantiation on the stack "
15322 "when instantiating a generic lambda!");
15323 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
15324 } else {
15325 // Enter a new function scope
15327 }
15328
15329 // Builtin functions cannot be defined.
15330 if (unsigned BuiltinID = FD->getBuiltinID()) {
15333 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15334 FD->setInvalidDecl();
15335 }
15336 }
15337
15338 // The return type of a function definition must be complete (C99 6.9.1p3).
15339 // C++23 [dcl.fct.def.general]/p2
15340 // The type of [...] the return for a function definition
15341 // shall not be a (possibly cv-qualified) class type that is incomplete
15342 // or abstract within the function body unless the function is deleted.
15343 QualType ResultType = FD->getReturnType();
15344 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15345 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15346 (RequireCompleteType(FD->getLocation(), ResultType,
15347 diag::err_func_def_incomplete_result) ||
15349 diag::err_abstract_type_in_decl,
15351 FD->setInvalidDecl();
15352
15353 if (FnBodyScope)
15354 PushDeclContext(FnBodyScope, FD);
15355
15356 // Check the validity of our function parameters
15357 if (BodyKind != FnBodyKind::Delete)
15359 /*CheckParameterNames=*/true);
15360
15361 // Add non-parameter declarations already in the function to the current
15362 // scope.
15363 if (FnBodyScope) {
15364 for (Decl *NPD : FD->decls()) {
15365 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15366 if (!NonParmDecl)
15367 continue;
15368 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15369 "parameters should not be in newly created FD yet");
15370
15371 // If the decl has a name, make it accessible in the current scope.
15372 if (NonParmDecl->getDeclName())
15373 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15374
15375 // Similarly, dive into enums and fish their constants out, making them
15376 // accessible in this scope.
15377 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15378 for (auto *EI : ED->enumerators())
15379 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15380 }
15381 }
15382 }
15383
15384 // Introduce our parameters into the function scope
15385 for (auto *Param : FD->parameters()) {
15386 Param->setOwningFunction(FD);
15387
15388 // If this has an identifier, add it to the scope stack.
15389 if (Param->getIdentifier() && FnBodyScope) {
15390 CheckShadow(FnBodyScope, Param);
15391
15392 PushOnScopeChains(Param, FnBodyScope);
15393 }
15394 }
15395
15396 // C++ [module.import/6] external definitions are not permitted in header
15397 // units. Deleted and Defaulted functions are implicitly inline (but the
15398 // inline state is not set at this point, so check the BodyKind explicitly).
15399 // FIXME: Consider an alternate location for the test where the inlined()
15400 // state is complete.
15401 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15402 !FD->isInvalidDecl() && !FD->isInlined() &&
15403 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15405 !FD->isTemplated() && !FD->isTemplateInstantiation()) {
15406 assert(FD->isThisDeclarationADefinition());
15407 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15408 FD->setInvalidDecl();
15409 }
15410
15411 // Ensure that the function's exception specification is instantiated.
15412 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15414
15415 // dllimport cannot be applied to non-inline function definitions.
15416 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15417 !FD->isTemplateInstantiation()) {
15418 assert(!FD->hasAttr<DLLExportAttr>());
15419 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15420 FD->setInvalidDecl();
15421 return D;
15422 }
15423 // We want to attach documentation to original Decl (which might be
15424 // a function template).
15426 if (getCurLexicalContext()->isObjCContainer() &&
15427 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15428 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15429 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15430
15431 return D;
15432}
15433
15434/// Given the set of return statements within a function body,
15435/// compute the variables that are subject to the named return value
15436/// optimization.
15437///
15438/// Each of the variables that is subject to the named return value
15439/// optimization will be marked as NRVO variables in the AST, and any
15440/// return statement that has a marked NRVO variable as its NRVO candidate can
15441/// use the named return value optimization.
15442///
15443/// This function applies a very simplistic algorithm for NRVO: if every return
15444/// statement in the scope of a variable has the same NRVO candidate, that
15445/// candidate is an NRVO variable.
15447 ReturnStmt **Returns = Scope->Returns.data();
15448
15449 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15450 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15451 if (!NRVOCandidate->isNRVOVariable())
15452 Returns[I]->setNRVOCandidate(nullptr);
15453 }
15454 }
15455}
15456
15458 // We can't delay parsing the body of a constexpr function template (yet).
15460 return false;
15461
15462 // We can't delay parsing the body of a function template with a deduced
15463 // return type (yet).
15464 if (D.getDeclSpec().hasAutoTypeSpec()) {
15465 // If the placeholder introduces a non-deduced trailing return type,
15466 // we can still delay parsing it.
15467 if (D.getNumTypeObjects()) {
15468 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15469 if (Outer.Kind == DeclaratorChunk::Function &&
15470 Outer.Fun.hasTrailingReturnType()) {
15471 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15472 return Ty.isNull() || !Ty->isUndeducedType();
15473 }
15474 }
15475 return false;
15476 }
15477
15478 return true;
15479}
15480
15482 // We cannot skip the body of a function (or function template) which is
15483 // constexpr, since we may need to evaluate its body in order to parse the
15484 // rest of the file.
15485 // We cannot skip the body of a function with an undeduced return type,
15486 // because any callers of that function need to know the type.
15487 if (const FunctionDecl *FD = D->getAsFunction()) {
15488 if (FD->isConstexpr())
15489 return false;
15490 // We can't simply call Type::isUndeducedType here, because inside template
15491 // auto can be deduced to a dependent type, which is not considered
15492 // "undeduced".
15493 if (FD->getReturnType()->getContainedDeducedType())
15494 return false;
15495 }
15497}
15498
15500 if (!Decl)
15501 return nullptr;
15502 if (FunctionDecl *FD = Decl->getAsFunction())
15503 FD->setHasSkippedBody();
15504 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15505 MD->setHasSkippedBody();
15506 return Decl;
15507}
15508
15510 return ActOnFinishFunctionBody(D, BodyArg, false);
15511}
15512
15513/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15514/// body.
15516public:
15517 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15519 if (!IsLambda)
15521 }
15522
15523private:
15524 Sema &S;
15525 bool IsLambda = false;
15526};
15527
15529 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15530
15531 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15532 if (EscapeInfo.count(BD))
15533 return EscapeInfo[BD];
15534
15535 bool R = false;
15536 const BlockDecl *CurBD = BD;
15537
15538 do {
15539 R = !CurBD->doesNotEscape();
15540 if (R)
15541 break;
15542 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15543 } while (CurBD);
15544
15545 return EscapeInfo[BD] = R;
15546 };
15547
15548 // If the location where 'self' is implicitly retained is inside a escaping
15549 // block, emit a diagnostic.
15550 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15552 if (IsOrNestedInEscapingBlock(P.second))
15553 S.Diag(P.first, diag::warn_implicitly_retains_self)
15554 << FixItHint::CreateInsertion(P.first, "self->");
15555}
15556
15558 bool IsInstantiation) {
15560 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15561
15562 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15563 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15564
15566 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15567
15568 if (getLangOpts().Coroutines && FSI->isCoroutine())
15570
15571 {
15572 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15573 // one is already popped when finishing the lambda in BuildLambdaExpr().
15574 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15575 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15576 if (FD) {
15577 FD->setBody(Body);
15578 FD->setWillHaveBody(false);
15580
15581 if (getLangOpts().CPlusPlus14) {
15582 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15583 FD->getReturnType()->isUndeducedType()) {
15584 // For a function with a deduced result type to return void,
15585 // the result type as written must be 'auto' or 'decltype(auto)',
15586 // possibly cv-qualified or constrained, but not ref-qualified.
15587 if (!FD->getReturnType()->getAs<AutoType>()) {
15588 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15589 << FD->getReturnType();
15590 FD->setInvalidDecl();
15591 } else {
15592 // Falling off the end of the function is the same as 'return;'.
15593 Expr *Dummy = nullptr;
15595 FD, dcl->getLocation(), Dummy,
15596 FD->getReturnType()->getAs<AutoType>()))
15597 FD->setInvalidDecl();
15598 }
15599 }
15600 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15601 // In C++11, we don't use 'auto' deduction rules for lambda call
15602 // operators because we don't support return type deduction.
15603 auto *LSI = getCurLambda();
15604 if (LSI->HasImplicitReturnType) {
15606
15607 // C++11 [expr.prim.lambda]p4:
15608 // [...] if there are no return statements in the compound-statement
15609 // [the deduced type is] the type void
15610 QualType RetType =
15611 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15612
15613 // Update the return type to the deduced type.
15614 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15615 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15616 Proto->getExtProtoInfo()));
15617 }
15618 }
15619
15620 // If the function implicitly returns zero (like 'main') or is naked,
15621 // don't complain about missing return statements.
15622 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15624
15625 // MSVC permits the use of pure specifier (=0) on function definition,
15626 // defined at class scope, warn about this non-standard construct.
15627 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15628 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15629
15630 if (!FD->isInvalidDecl()) {
15631 // Don't diagnose unused parameters of defaulted, deleted or naked
15632 // functions.
15633 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15634 !FD->hasAttr<NakedAttr>())
15637 FD->getReturnType(), FD);
15638
15639 // If this is a structor, we need a vtable.
15640 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15641 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15642 else if (CXXDestructorDecl *Destructor =
15643 dyn_cast<CXXDestructorDecl>(FD))
15644 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15645
15646 // Try to apply the named return value optimization. We have to check
15647 // if we can do this here because lambdas keep return statements around
15648 // to deduce an implicit return type.
15649 if (FD->getReturnType()->isRecordType() &&
15651 computeNRVO(Body, FSI);
15652 }
15653
15654 // GNU warning -Wmissing-prototypes:
15655 // Warn if a global function is defined without a previous
15656 // prototype declaration. This warning is issued even if the
15657 // definition itself provides a prototype. The aim is to detect
15658 // global functions that fail to be declared in header files.
15659 const FunctionDecl *PossiblePrototype = nullptr;
15660 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15661 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15662
15663 if (PossiblePrototype) {
15664 // We found a declaration that is not a prototype,
15665 // but that could be a zero-parameter prototype
15666 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15667 TypeLoc TL = TI->getTypeLoc();
15669 Diag(PossiblePrototype->getLocation(),
15670 diag::note_declaration_not_a_prototype)
15671 << (FD->getNumParams() != 0)
15673 FTL.getRParenLoc(), "void")
15674 : FixItHint{});
15675 }
15676 } else {
15677 // Returns true if the token beginning at this Loc is `const`.
15678 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15679 const LangOptions &LangOpts) {
15680 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15681 if (LocInfo.first.isInvalid())
15682 return false;
15683
15684 bool Invalid = false;
15685 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15686 if (Invalid)
15687 return false;
15688
15689 if (LocInfo.second > Buffer.size())
15690 return false;
15691
15692 const char *LexStart = Buffer.data() + LocInfo.second;
15693 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15694
15695 return StartTok.consume_front("const") &&
15696 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15697 StartTok.startswith("/*") || StartTok.startswith("//"));
15698 };
15699
15700 auto findBeginLoc = [&]() {
15701 // If the return type has `const` qualifier, we want to insert
15702 // `static` before `const` (and not before the typename).
15703 if ((FD->getReturnType()->isAnyPointerType() &&
15706 // But only do this if we can determine where the `const` is.
15707
15708 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15709 getLangOpts()))
15710
15711 return FD->getBeginLoc();
15712 }
15713 return FD->getTypeSpecStartLoc();
15714 };
15716 diag::note_static_for_internal_linkage)
15717 << /* function */ 1
15718 << (FD->getStorageClass() == SC_None
15719 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15720 : FixItHint{});
15721 }
15722 }
15723
15724 // We might not have found a prototype because we didn't wish to warn on
15725 // the lack of a missing prototype. Try again without the checks for
15726 // whether we want to warn on the missing prototype.
15727 if (!PossiblePrototype)
15728 (void)FindPossiblePrototype(FD, PossiblePrototype);
15729
15730 // If the function being defined does not have a prototype, then we may
15731 // need to diagnose it as changing behavior in C2x because we now know
15732 // whether the function accepts arguments or not. This only handles the
15733 // case where the definition has no prototype but does have parameters
15734 // and either there is no previous potential prototype, or the previous
15735 // potential prototype also has no actual prototype. This handles cases
15736 // like:
15737 // void f(); void f(a) int a; {}
15738 // void g(a) int a; {}
15739 // See MergeFunctionDecl() for other cases of the behavior change
15740 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15741 // type without a prototype.
15742 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15743 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15744 !PossiblePrototype->isImplicit()))) {
15745 // The function definition has parameters, so this will change behavior
15746 // in C2x. If there is a possible prototype, it comes before the
15747 // function definition.
15748 // FIXME: The declaration may have already been diagnosed as being
15749 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15750 // there's no way to test for the "changes behavior" condition in
15751 // SemaType.cpp when forming the declaration's function type. So, we do
15752 // this awkward dance instead.
15753 //
15754 // If we have a possible prototype and it declares a function with a
15755 // prototype, we don't want to diagnose it; if we have a possible
15756 // prototype and it has no prototype, it may have already been
15757 // diagnosed in SemaType.cpp as deprecated depending on whether
15758 // -Wstrict-prototypes is enabled. If we already warned about it being
15759 // deprecated, add a note that it also changes behavior. If we didn't
15760 // warn about it being deprecated (because the diagnostic is not
15761 // enabled), warn now that it is deprecated and changes behavior.
15762
15763 // This K&R C function definition definitely changes behavior in C2x,
15764 // so diagnose it.
15765 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15766 << /*definition*/ 1 << /* not supported in C2x */ 0;
15767
15768 // If we have a possible prototype for the function which is a user-
15769 // visible declaration, we already tested that it has no prototype.
15770 // This will change behavior in C2x. This gets a warning rather than a
15771 // note because it's the same behavior-changing problem as with the
15772 // definition.
15773 if (PossiblePrototype)
15774 Diag(PossiblePrototype->getLocation(),
15775 diag::warn_non_prototype_changes_behavior)
15776 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
15777 << /*definition*/ 1;
15778 }
15779
15780 // Warn on CPUDispatch with an actual body.
15781 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
15782 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
15783 if (!CmpndBody->body_empty())
15784 Diag(CmpndBody->body_front()->getBeginLoc(),
15785 diag::warn_dispatch_body_ignored);
15786
15787 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
15788 const CXXMethodDecl *KeyFunction;
15789 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
15790 MD->isVirtual() &&
15791 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
15792 MD == KeyFunction->getCanonicalDecl()) {
15793 // Update the key-function state if necessary for this ABI.
15794 if (FD->isInlined() &&
15797
15798 // If the newly-chosen key function is already defined, then we
15799 // need to mark the vtable as used retroactively.
15800 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
15801 const FunctionDecl *Definition;
15802 if (KeyFunction && KeyFunction->isDefined(Definition))
15803 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
15804 } else {
15805 // We just defined they key function; mark the vtable as used.
15806 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
15807 }
15808 }
15809 }
15810
15811 assert(
15812 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
15813 "Function parsing confused");
15814 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
15815 assert(MD == getCurMethodDecl() && "Method parsing confused");
15816 MD->setBody(Body);
15817 if (!MD->isInvalidDecl()) {
15819 MD->getReturnType(), MD);
15820
15821 if (Body)
15822 computeNRVO(Body, FSI);
15823 }
15824 if (FSI->ObjCShouldCallSuper) {
15825 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
15826 << MD->getSelector().getAsString();
15827 FSI->ObjCShouldCallSuper = false;
15828 }
15830 const ObjCMethodDecl *InitMethod = nullptr;
15831 bool isDesignated =
15832 MD->isDesignatedInitializerForTheInterface(&InitMethod);
15833 assert(isDesignated && InitMethod);
15834 (void)isDesignated;
15835
15836 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
15837 auto IFace = MD->getClassInterface();
15838 if (!IFace)
15839 return false;
15840 auto SuperD = IFace->getSuperClass();
15841 if (!SuperD)
15842 return false;
15843 return SuperD->getIdentifier() ==
15844 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
15845 };
15846 // Don't issue this warning for unavailable inits or direct subclasses
15847 // of NSObject.
15848 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
15849 Diag(MD->getLocation(),
15850 diag::warn_objc_designated_init_missing_super_call);
15851 Diag(InitMethod->getLocation(),
15852 diag::note_objc_designated_init_marked_here);
15853 }
15855 }
15856 if (FSI->ObjCWarnForNoInitDelegation) {
15857 // Don't issue this warning for unavaialable inits.
15858 if (!MD->isUnavailable())
15859 Diag(MD->getLocation(),
15860 diag::warn_objc_secondary_init_missing_init_call);
15861 FSI->ObjCWarnForNoInitDelegation = false;
15862 }
15863
15865 } else {
15866 // Parsing the function declaration failed in some way. Pop the fake scope
15867 // we pushed on.
15868 PopFunctionScopeInfo(ActivePolicy, dcl);
15869 return nullptr;
15870 }
15871
15872 if (Body && FSI->HasPotentialAvailabilityViolations)
15874
15875 assert(!FSI->ObjCShouldCallSuper &&
15876 "This should only be set for ObjC methods, which should have been "
15877 "handled in the block above.");
15878
15879 // Verify and clean out per-function state.
15880 if (Body && (!FD || !FD->isDefaulted())) {
15881 // C++ constructors that have function-try-blocks can't have return
15882 // statements in the handlers of that block. (C++ [except.handle]p14)
15883 // Verify this.
15884 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15885 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15886
15887 // Verify that gotos and switch cases don't jump into scopes illegally.
15890
15891 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15892 if (!Destructor->getParent()->isDependentType())
15893 CheckDestructor(Destructor);
15894
15895 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15896 Destructor->getParent());
15897 }
15898
15899 // If any errors have occurred, clear out any temporaries that may have
15900 // been leftover. This ensures that these temporaries won't be picked up
15901 // for deletion in some later function.
15903 getDiagnostics().getSuppressAllDiagnostics()) {
15905 }
15906 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15907 // Since the body is valid, issue any analysis-based warnings that are
15908 // enabled.
15909 ActivePolicy = &WP;
15910 }
15911
15912 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15914 FD->setInvalidDecl();
15915
15916 if (FD && FD->hasAttr<NakedAttr>()) {
15917 for (const Stmt *S : Body->children()) {
15918 // Allow local register variables without initializer as they don't
15919 // require prologue.
15920 bool RegisterVariables = false;
15921 if (auto *DS = dyn_cast<DeclStmt>(S)) {
15922 for (const auto *Decl : DS->decls()) {
15923 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15924 RegisterVariables =
15925 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15926 if (!RegisterVariables)
15927 break;
15928 }
15929 }
15930 }
15931 if (RegisterVariables)
15932 continue;
15933 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15934 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15935 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15936 FD->setInvalidDecl();
15937 break;
15938 }
15939 }
15940 }
15941
15942 assert(ExprCleanupObjects.size() ==
15943 ExprEvalContexts.back().NumCleanupObjects &&
15944 "Leftover temporaries in function");
15945 assert(!Cleanup.exprNeedsCleanups() &&
15946 "Unaccounted cleanups in function");
15947 assert(MaybeODRUseExprs.empty() &&
15948 "Leftover expressions for odr-use checking");
15949 }
15950 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15951 // the declaration context below. Otherwise, we're unable to transform
15952 // 'this' expressions when transforming immediate context functions.
15953
15954 if (!IsInstantiation)
15956
15957 PopFunctionScopeInfo(ActivePolicy, dcl);
15958 // If any errors have occurred, clear out any temporaries that may have
15959 // been leftover. This ensures that these temporaries won't be picked up for
15960 // deletion in some later function.
15963 }
15964
15965 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
15966 !LangOpts.OMPTargetTriples.empty())) ||
15967 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15968 auto ES = getEmissionStatus(FD);
15971 DeclsToCheckForDeferredDiags.insert(FD);
15972 }
15973
15974 if (FD && !FD->isDeleted())
15975 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15976
15977 return dcl;
15978}
15979
15980/// When we finish delayed parsing of an attribute, we must attach it to the
15981/// relevant Decl.
15983 ParsedAttributes &Attrs) {
15984 // Always attach attributes to the underlying decl.
15985 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15986 D = TD->getTemplatedDecl();
15987 ProcessDeclAttributeList(S, D, Attrs);
15988
15989 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15990 if (Method->isStatic())
15992}
15993
15994/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15995/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15997 IdentifierInfo &II, Scope *S) {
15998 // It is not valid to implicitly define a function in C2x.
16000 "Implicit function declarations aren't allowed in this language mode");
16001
16002 // Find the scope in which the identifier is injected and the corresponding
16003 // DeclContext.
16004 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16005 // In that case, we inject the declaration into the translation unit scope
16006 // instead.
16007 Scope *BlockScope = S;
16008 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16009 BlockScope = BlockScope->getParent();
16010
16011 // Loop until we find a DeclContext that is either a function/method or the
16012 // translation unit, which are the only two valid places to implicitly define
16013 // a function. This avoids accidentally defining the function within a tag
16014 // declaration, for example.
16015 Scope *ContextScope = BlockScope;
16016 while (!ContextScope->getEntity() ||
16017 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16018 !ContextScope->getEntity()->isTranslationUnit()))
16019 ContextScope = ContextScope->getParent();
16020 ContextRAII SavedContext(*this, ContextScope->getEntity());
16021
16022 // Before we produce a declaration for an implicitly defined
16023 // function, see whether there was a locally-scoped declaration of
16024 // this name as a function or variable. If so, use that
16025 // (non-visible) declaration, and complain about it.
16026 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16027 if (ExternCPrev) {
16028 // We still need to inject the function into the enclosing block scope so
16029 // that later (non-call) uses can see it.
16030 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16031
16032 // C89 footnote 38:
16033 // If in fact it is not defined as having type "function returning int",
16034 // the behavior is undefined.
16035 if (!isa<FunctionDecl>(ExternCPrev) ||
16037 cast<FunctionDecl>(ExternCPrev)->getType(),
16039 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16040 << ExternCPrev << !getLangOpts().C99;
16041 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16042 return ExternCPrev;
16043 }
16044 }
16045
16046 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16047 unsigned diag_id;
16048 if (II.getName().startswith("__builtin_"))
16049 diag_id = diag::warn_builtin_unknown;
16050 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16051 else if (getLangOpts().C99)
16052 diag_id = diag::ext_implicit_function_decl_c99;
16053 else
16054 diag_id = diag::warn_implicit_function_decl;
16055
16056 TypoCorrection Corrected;
16057 // Because typo correction is expensive, only do it if the implicit
16058 // function declaration is going to be treated as an error.
16059 //
16060 // Perform the correction before issuing the main diagnostic, as some
16061 // consumers use typo-correction callbacks to enhance the main diagnostic.
16062 if (S && !ExternCPrev &&
16065 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16066 S, nullptr, CCC, CTK_NonError);
16067 }
16068
16069 Diag(Loc, diag_id) << &II;
16070 if (Corrected) {
16071 // If the correction is going to suggest an implicitly defined function,
16072 // skip the correction as not being a particularly good idea.
16073 bool Diagnose = true;
16074 if (const auto *D = Corrected.getCorrectionDecl())
16075 Diagnose = !D->isImplicit();
16076 if (Diagnose)
16077 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16078 /*ErrorRecovery*/ false);
16079 }
16080
16081 // If we found a prior declaration of this function, don't bother building
16082 // another one. We've already pushed that one into scope, so there's nothing
16083 // more to do.
16084 if (ExternCPrev)
16085 return ExternCPrev;
16086
16087 // Set a Declarator for the implicit definition: int foo();
16088 const char *Dummy;
16089 AttributeFactory attrFactory;
16090 DeclSpec DS(attrFactory);
16091 unsigned DiagID;
16092 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16094 (void)Error; // Silence warning.
16095 assert(!Error && "Error setting up implicit decl!");
16096 SourceLocation NoLoc;
16098 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16099 /*IsAmbiguous=*/false,
16100 /*LParenLoc=*/NoLoc,
16101 /*Params=*/nullptr,
16102 /*NumParams=*/0,
16103 /*EllipsisLoc=*/NoLoc,
16104 /*RParenLoc=*/NoLoc,
16105 /*RefQualifierIsLvalueRef=*/true,
16106 /*RefQualifierLoc=*/NoLoc,
16107 /*MutableLoc=*/NoLoc, EST_None,
16108 /*ESpecRange=*/SourceRange(),
16109 /*Exceptions=*/nullptr,
16110 /*ExceptionRanges=*/nullptr,
16111 /*NumExceptions=*/0,
16112 /*NoexceptExpr=*/nullptr,
16113 /*ExceptionSpecTokens=*/nullptr,
16114 /*DeclsInPrototype=*/std::nullopt,
16115 Loc, Loc, D),
16116 std::move(DS.getAttributes()), SourceLocation());
16117 D.SetIdentifier(&II, Loc);
16118
16119 // Insert this function into the enclosing block scope.
16120 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16121 FD->setImplicit();
16122
16124
16125 return FD;
16126}
16127
16128/// If this function is a C++ replaceable global allocation function
16129/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16130/// adds any function attributes that we know a priori based on the standard.
16131///
16132/// We need to check for duplicate attributes both here and where user-written
16133/// attributes are applied to declarations.
16135 FunctionDecl *FD) {
16136 if (FD->isInvalidDecl())
16137 return;
16138
16139 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16140 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16141 return;
16142
16143 std::optional<unsigned> AlignmentParam;
16144 bool IsNothrow = false;
16145 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16146 return;
16147
16148 // C++2a [basic.stc.dynamic.allocation]p4:
16149 // An allocation function that has a non-throwing exception specification
16150 // indicates failure by returning a null pointer value. Any other allocation
16151 // function never returns a null pointer value and indicates failure only by
16152 // throwing an exception [...]
16153 //
16154 // However, -fcheck-new invalidates this possible assumption, so don't add
16155 // NonNull when that is enabled.
16156 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16157 !getLangOpts().CheckNew)
16158 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16159
16160 // C++2a [basic.stc.dynamic.allocation]p2:
16161 // An allocation function attempts to allocate the requested amount of
16162 // storage. [...] If the request succeeds, the value returned by a
16163 // replaceable allocation function is a [...] pointer value p0 different
16164 // from any previously returned value p1 [...]
16165 //
16166 // However, this particular information is being added in codegen,
16167 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16168
16169 // C++2a [basic.stc.dynamic.allocation]p2:
16170 // An allocation function attempts to allocate the requested amount of
16171 // storage. If it is successful, it returns the address of the start of a
16172 // block of storage whose length in bytes is at least as large as the
16173 // requested size.
16174 if (!FD->hasAttr<AllocSizeAttr>()) {
16175 FD->addAttr(AllocSizeAttr::CreateImplicit(
16176 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16177 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16178 }
16179
16180 // C++2a [basic.stc.dynamic.allocation]p3:
16181 // For an allocation function [...], the pointer returned on a successful
16182 // call shall represent the address of storage that is aligned as follows:
16183 // (3.1) If the allocation function takes an argument of type
16184 // std​::​align_­val_­t, the storage will have the alignment
16185 // specified by the value of this argument.
16186 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16187 FD->addAttr(AllocAlignAttr::CreateImplicit(
16188 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16189 }
16190
16191 // FIXME:
16192 // C++2a [basic.stc.dynamic.allocation]p3:
16193 // For an allocation function [...], the pointer returned on a successful
16194 // call shall represent the address of storage that is aligned as follows:
16195 // (3.2) Otherwise, if the allocation function is named operator new[],
16196 // the storage is aligned for any object that does not have
16197 // new-extended alignment ([basic.align]) and is no larger than the
16198 // requested size.
16199 // (3.3) Otherwise, the storage is aligned for any object that does not
16200 // have new-extended alignment and is of the requested size.
16201}
16202
16203/// Adds any function attributes that we know a priori based on
16204/// the declaration of this function.
16205///
16206/// These attributes can apply both to implicitly-declared builtins
16207/// (like __builtin___printf_chk) or to library-declared functions
16208/// like NSLog or printf.
16209///
16210/// We need to check for duplicate attributes both here and where user-written
16211/// attributes are applied to declarations.
16213 if (FD->isInvalidDecl())
16214 return;
16215
16216 // If this is a built-in function, map its builtin attributes to
16217 // actual attributes.
16218 if (unsigned BuiltinID = FD->getBuiltinID()) {
16219 // Handle printf-formatting attributes.
16220 unsigned FormatIdx;
16221 bool HasVAListArg;
16222 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16223 if (!FD->hasAttr<FormatAttr>()) {
16224 const char *fmt = "printf";
16225 unsigned int NumParams = FD->getNumParams();
16226 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16227 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16228 fmt = "NSString";
16229 FD->addAttr(FormatAttr::CreateImplicit(Context,
16230 &Context.Idents.get(fmt),
16231 FormatIdx+1,
16232 HasVAListArg ? 0 : FormatIdx+2,
16233 FD->getLocation()));
16234 }
16235 }
16236 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16237 HasVAListArg)) {
16238 if (!FD->hasAttr<FormatAttr>())
16239 FD->addAttr(FormatAttr::CreateImplicit(Context,
16240 &Context.Idents.get("scanf"),
16241 FormatIdx+1,
16242 HasVAListArg ? 0 : FormatIdx+2,
16243 FD->getLocation()));
16244 }
16245
16246 // Handle automatically recognized callbacks.
16247 SmallVector<int, 4> Encoding;
16248 if (!FD->hasAttr<CallbackAttr>() &&
16249 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16250 FD->addAttr(CallbackAttr::CreateImplicit(
16251 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16252
16253 // Mark const if we don't care about errno and/or floating point exceptions
16254 // that are the only thing preventing the function from being const. This
16255 // allows IRgen to use LLVM intrinsics for such functions.
16256 bool NoExceptions =
16258 bool ConstWithoutErrnoAndExceptions =
16260 bool ConstWithoutExceptions =
16262 if (!FD->hasAttr<ConstAttr>() &&
16263 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16264 (!ConstWithoutErrnoAndExceptions ||
16265 (!getLangOpts().MathErrno && NoExceptions)) &&
16266 (!ConstWithoutExceptions || NoExceptions))
16267 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16268
16269 // We make "fma" on GNU or Windows const because we know it does not set
16270 // errno in those environments even though it could set errno based on the
16271 // C standard.
16272 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16273 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16274 !FD->hasAttr<ConstAttr>()) {
16275 switch (BuiltinID) {
16276 case Builtin::BI__builtin_fma:
16277 case Builtin::BI__builtin_fmaf:
16278 case Builtin::BI__builtin_fmal:
16279 case Builtin::BIfma:
16280 case Builtin::BIfmaf:
16281 case Builtin::BIfmal:
16282 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16283 break;
16284 default:
16285 break;
16286 }
16287 }
16288
16289 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16290 !FD->hasAttr<ReturnsTwiceAttr>())
16291 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16292 FD->getLocation()));
16293 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16294 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16295 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16296 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16297 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16298 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16299 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16300 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16301 // Add the appropriate attribute, depending on the CUDA compilation mode
16302 // and which target the builtin belongs to. For example, during host
16303 // compilation, aux builtins are __device__, while the rest are __host__.
16304 if (getLangOpts().CUDAIsDevice !=
16306 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16307 else
16308 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16309 }
16310
16311 // Add known guaranteed alignment for allocation functions.
16312 switch (BuiltinID) {
16313 case Builtin::BImemalign:
16314 case Builtin::BIaligned_alloc:
16315 if (!FD->hasAttr<AllocAlignAttr>())
16316 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16317 FD->getLocation()));
16318 break;
16319 default:
16320 break;
16321 }
16322
16323 // Add allocsize attribute for allocation functions.
16324 switch (BuiltinID) {
16325 case Builtin::BIcalloc:
16326 FD->addAttr(AllocSizeAttr::CreateImplicit(
16327 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16328 break;
16329 case Builtin::BImemalign:
16330 case Builtin::BIaligned_alloc:
16331 case Builtin::BIrealloc:
16332 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16333 ParamIdx(), FD->getLocation()));
16334 break;
16335 case Builtin::BImalloc:
16336 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16337 ParamIdx(), FD->getLocation()));
16338 break;
16339 default:
16340 break;
16341 }
16342
16343 // Add lifetime attribute to std::move, std::fowrard et al.
16344 switch (BuiltinID) {
16345 case Builtin::BIaddressof:
16346 case Builtin::BI__addressof:
16347 case Builtin::BI__builtin_addressof:
16348 case Builtin::BIas_const:
16349 case Builtin::BIforward:
16350 case Builtin::BIforward_like:
16351 case Builtin::BImove:
16352 case Builtin::BImove_if_noexcept:
16353 if (ParmVarDecl *P = FD->getParamDecl(0u);
16354 !P->hasAttr<LifetimeBoundAttr>())
16355 P->addAttr(
16356 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16357 break;
16358 default:
16359 break;
16360 }
16361 }
16362
16364
16365 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16366 // throw, add an implicit nothrow attribute to any extern "C" function we come
16367 // across.
16368 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16369 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16370 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16371 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16372 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16373 }
16374
16375 IdentifierInfo *Name = FD->getIdentifier();
16376 if (!Name)
16377 return;
16378 if ((!getLangOpts().CPlusPlus &&
16380 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16381 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16383 // Okay: this could be a libc/libm/Objective-C function we know
16384 // about.
16385 } else
16386 return;
16387
16388 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16389 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16390 // target-specific builtins, perhaps?
16391 if (!FD->hasAttr<FormatAttr>())
16392 FD->addAttr(FormatAttr::CreateImplicit(Context,
16393 &Context.Idents.get("printf"), 2,
16394 Name->isStr("vasprintf") ? 0 : 3,
16395 FD->getLocation()));
16396 }
16397
16398 if (Name->isStr("__CFStringMakeConstantString")) {
16399 // We already have a __builtin___CFStringMakeConstantString,
16400 // but builds that use -fno-constant-cfstrings don't go through that.
16401 if (!FD->hasAttr<FormatArgAttr>())
16402 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16403 FD->getLocation()));
16404 }
16405}
16406
16408 TypeSourceInfo *TInfo) {
16409 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16410 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16411
16412 if (!TInfo) {
16413 assert(D.isInvalidType() && "no declarator info for valid type");
16415 }
16416
16417 // Scope manipulation handled by caller.
16418 TypedefDecl *NewTD =
16420 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16421
16422 // Bail out immediately if we have an invalid declaration.
16423 if (D.isInvalidType()) {
16424 NewTD->setInvalidDecl();
16425 return NewTD;
16426 }
16427
16430 Diag(NewTD->getLocation(), diag::err_module_private_local)
16431 << 2 << NewTD
16435 else
16436 NewTD->setModulePrivate();
16437 }
16438
16439 // C++ [dcl.typedef]p8:
16440 // If the typedef declaration defines an unnamed class (or
16441 // enum), the first typedef-name declared by the declaration
16442 // to be that class type (or enum type) is used to denote the
16443 // class type (or enum type) for linkage purposes only.
16444 // We need to check whether the type was declared in the declaration.
16445 switch (D.getDeclSpec().getTypeSpecType()) {
16446 case TST_enum:
16447 case TST_struct:
16448 case TST_interface:
16449 case TST_union:
16450 case TST_class: {
16451 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16452 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16453 break;
16454 }
16455
16456 default:
16457 break;
16458 }
16459
16460 return NewTD;
16461}
16462
16463/// Check that this is a valid underlying type for an enum declaration.
16465 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16466 QualType T = TI->getType();
16467
16468 if (T->isDependentType())
16469 return false;
16470
16471 // This doesn't use 'isIntegralType' despite the error message mentioning
16472 // integral type because isIntegralType would also allow enum types in C.
16473 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16474 if (BT->isInteger())
16475 return false;
16476
16477 if (T->isBitIntType())
16478 return false;
16479
16480 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
16481}
16482
16483/// Check whether this is a valid redeclaration of a previous enumeration.
16484/// \return true if the redeclaration was invalid.
16486 QualType EnumUnderlyingTy, bool IsFixed,
16487 const EnumDecl *Prev) {
16488 if (IsScoped != Prev->isScoped()) {
16489 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16490 << Prev->isScoped();
16491 Diag(Prev->getLocation(), diag::note_previous_declaration);
16492 return true;
16493 }
16494
16495 if (IsFixed && Prev->isFixed()) {
16496 if (!EnumUnderlyingTy->isDependentType() &&
16497 !Prev->getIntegerType()->isDependentType() &&
16498 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16499 Prev->getIntegerType())) {
16500 // TODO: Highlight the underlying type of the redeclaration.
16501 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16502 << EnumUnderlyingTy << Prev->getIntegerType();
16503 Diag(Prev->getLocation(), diag::note_previous_declaration)
16504 << Prev->getIntegerTypeRange();
16505 return true;
16506 }
16507 } else if (IsFixed != Prev->isFixed()) {
16508 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16509 << Prev->isFixed();
16510 Diag(Prev->getLocation(), diag::note_previous_declaration);
16511 return true;
16512 }
16513
16514 return false;
16515}
16516
16517/// Get diagnostic %select index for tag kind for
16518/// redeclaration diagnostic message.
16519/// WARNING: Indexes apply to particular diagnostics only!
16520///
16521/// \returns diagnostic %select index.
16522static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16523 switch (Tag) {
16524 case TTK_Struct: return 0;
16525 case TTK_Interface: return 1;
16526 case TTK_Class: return 2;
16527 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16528 }
16529}
16530
16531/// Determine if tag kind is a class-key compatible with
16532/// class for redeclaration (class, struct, or __interface).
16533///
16534/// \returns true iff the tag kind is compatible.
16535static bool isClassCompatTagKind(TagTypeKind Tag)
16536{
16537 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
16538}
16539
16541 TagTypeKind TTK) {
16542 if (isa<TypedefDecl>(PrevDecl))
16543 return NTK_Typedef;
16544 else if (isa<TypeAliasDecl>(PrevDecl))
16545 return NTK_TypeAlias;
16546 else if (isa<ClassTemplateDecl>(PrevDecl))
16547 return NTK_Template;
16548 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16549 return NTK_TypeAliasTemplate;
16550 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16552 switch (TTK) {
16553 case TTK_Struct:
16554 case TTK_Interface:
16555 case TTK_Class:
16556 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16557 case TTK_Union:
16558 return NTK_NonUnion;
16559 case TTK_Enum:
16560 return NTK_NonEnum;
16561 }
16562 llvm_unreachable("invalid TTK");
16563}
16564
16565/// Determine whether a tag with a given kind is acceptable
16566/// as a redeclaration of the given tag declaration.
16567///
16568/// \returns true if the new tag kind is acceptable, false otherwise.
16570 TagTypeKind NewTag, bool isDefinition,
16571 SourceLocation NewTagLoc,
16572 const IdentifierInfo *Name) {
16573 // C++ [dcl.type.elab]p3:
16574 // The class-key or enum keyword present in the
16575 // elaborated-type-specifier shall agree in kind with the
16576 // declaration to which the name in the elaborated-type-specifier
16577 // refers. This rule also applies to the form of
16578 // elaborated-type-specifier that declares a class-name or
16579 // friend class since it can be construed as referring to the
16580 // definition of the class. Thus, in any
16581 // elaborated-type-specifier, the enum keyword shall be used to
16582 // refer to an enumeration (7.2), the union class-key shall be
16583 // used to refer to a union (clause 9), and either the class or
16584 // struct class-key shall be used to refer to a class (clause 9)
16585 // declared using the class or struct class-key.
16586 TagTypeKind OldTag = Previous->getTagKind();
16587 if (OldTag != NewTag &&
16588 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16589 return false;
16590
16591 // Tags are compatible, but we might still want to warn on mismatched tags.
16592 // Non-class tags can't be mismatched at this point.
16593 if (!isClassCompatTagKind(NewTag))
16594 return true;
16595
16596 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16597 // by our warning analysis. We don't want to warn about mismatches with (eg)
16598 // declarations in system headers that are designed to be specialized, but if
16599 // a user asks us to warn, we should warn if their code contains mismatched
16600 // declarations.
16601 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16602 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16603 Loc);
16604 };
16605 if (IsIgnoredLoc(NewTagLoc))
16606 return true;
16607
16608 auto IsIgnored = [&](const TagDecl *Tag) {
16609 return IsIgnoredLoc(Tag->getLocation());
16610 };
16611 while (IsIgnored(Previous)) {
16612 Previous = Previous->getPreviousDecl();
16613 if (!Previous)
16614 return true;
16615 OldTag = Previous->getTagKind();
16616 }
16617
16618 bool isTemplate = false;
16619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16620 isTemplate = Record->getDescribedClassTemplate();
16621
16623 if (OldTag != NewTag) {
16624 // In a template instantiation, do not offer fix-its for tag mismatches
16625 // since they usually mess up the template instead of fixing the problem.
16626 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16627 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16628 << getRedeclDiagFromTagKind(OldTag);
16629 // FIXME: Note previous location?
16630 }
16631 return true;
16632 }
16633
16634 if (isDefinition) {
16635 // On definitions, check all previous tags and issue a fix-it for each
16636 // one that doesn't match the current tag.
16637 if (Previous->getDefinition()) {
16638 // Don't suggest fix-its for redefinitions.
16639 return true;
16640 }
16641
16642 bool previousMismatch = false;
16643 for (const TagDecl *I : Previous->redecls()) {
16644 if (I->getTagKind() != NewTag) {
16645 // Ignore previous declarations for which the warning was disabled.
16646 if (IsIgnored(I))
16647 continue;
16648
16649 if (!previousMismatch) {
16650 previousMismatch = true;
16651 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16652 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16653 << getRedeclDiagFromTagKind(I->getTagKind());
16654 }
16655 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16656 << getRedeclDiagFromTagKind(NewTag)
16657 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16658 TypeWithKeyword::getTagTypeKindName(NewTag));
16659 }
16660 }
16661 return true;
16662 }
16663
16664 // Identify the prevailing tag kind: this is the kind of the definition (if
16665 // there is a non-ignored definition), or otherwise the kind of the prior
16666 // (non-ignored) declaration.
16667 const TagDecl *PrevDef = Previous->getDefinition();
16668 if (PrevDef && IsIgnored(PrevDef))
16669 PrevDef = nullptr;
16670 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16671 if (Redecl->getTagKind() != NewTag) {
16672 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16673 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16674 << getRedeclDiagFromTagKind(OldTag);
16675 Diag(Redecl->getLocation(), diag::note_previous_use);
16676
16677 // If there is a previous definition, suggest a fix-it.
16678 if (PrevDef) {
16679 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16682 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16683 }
16684 }
16685
16686 return true;
16687}
16688
16689/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16690/// from an outer enclosing namespace or file scope inside a friend declaration.
16691/// This should provide the commented out code in the following snippet:
16692/// namespace N {
16693/// struct X;
16694/// namespace M {
16695/// struct Y { friend struct /*N::*/ X; };
16696/// }
16697/// }
16699 SourceLocation NameLoc) {
16700 // While the decl is in a namespace, do repeated lookup of that name and see
16701 // if we get the same namespace back. If we do not, continue until
16702 // translation unit scope, at which point we have a fully qualified NNS.
16705 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16706 // This tag should be declared in a namespace, which can only be enclosed by
16707 // other namespaces. Bail if there's an anonymous namespace in the chain.
16708 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16709 if (!Namespace || Namespace->isAnonymousNamespace())
16710 return FixItHint();
16711 IdentifierInfo *II = Namespace->getIdentifier();
16712 Namespaces.push_back(II);
16713 NamedDecl *Lookup = SemaRef.LookupSingleName(
16714 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16715 if (Lookup == Namespace)
16716 break;
16717 }
16718
16719 // Once we have all the namespaces, reverse them to go outermost first, and
16720 // build an NNS.
16721 SmallString<64> Insertion;
16722 llvm::raw_svector_ostream OS(Insertion);
16723 if (DC->isTranslationUnit())
16724 OS << "::";
16725 std::reverse(Namespaces.begin(), Namespaces.end());
16726 for (auto *II : Namespaces)
16727 OS << II->getName() << "::";
16728 return FixItHint::CreateInsertion(NameLoc, Insertion);
16729}
16730
16731/// Determine whether a tag originally declared in context \p OldDC can
16732/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16733/// found a declaration in \p OldDC as a previous decl, perhaps through a
16734/// using-declaration).
16736 DeclContext *NewDC) {
16737 OldDC = OldDC->getRedeclContext();
16738 NewDC = NewDC->getRedeclContext();
16739
16740 if (OldDC->Equals(NewDC))
16741 return true;
16742
16743 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16744 // encloses the other).
16745 if (S.getLangOpts().MSVCCompat &&
16746 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16747 return true;
16748
16749 return false;
16750}
16751
16752/// This is invoked when we see 'struct foo' or 'struct {'. In the
16753/// former case, Name will be non-null. In the later case, Name will be null.
16754/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
16755/// reference/declaration/definition of a tag.
16756///
16757/// \param IsTypeSpecifier \c true if this is a type-specifier (or
16758/// trailing-type-specifier) other than one in an alias-declaration.
16759///
16760/// \param SkipBody If non-null, will be set to indicate if the caller should
16761/// skip the definition of this tag and treat it as if it were a declaration.
16763Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16764 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16765 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16766 SourceLocation ModulePrivateLoc,
16767 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16768 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16769 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16770 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16771 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16772 // If this is not a definition, it must have a name.
16773 IdentifierInfo *OrigName = Name;
16774 assert((Name != nullptr || TUK == TUK_Definition) &&
16775 "Nameless record must be a definition!");
16776 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
16777
16778 OwnedDecl = false;
16779 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16780 bool ScopedEnum = ScopedEnumKWLoc.isValid();
16781
16782 // FIXME: Check member specializations more carefully.
16783 bool isMemberSpecialization = false;
16784 bool Invalid = false;
16785
16786 // We only need to do this matching if we have template parameters
16787 // or a scope specifier, which also conveniently avoids this work
16788 // for non-C++ cases.
16789 if (TemplateParameterLists.size() > 0 ||
16790 (SS.isNotEmpty() && TUK != TUK_Reference)) {
16791 if (TemplateParameterList *TemplateParams =
16793 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16794 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
16795 if (Kind == TTK_Enum) {
16796 Diag(KWLoc, diag::err_enum_template);
16797 return true;
16798 }
16799
16800 if (TemplateParams->size() > 0) {
16801 // This is a declaration or definition of a class template (which may
16802 // be a member of another template).
16803
16804 if (Invalid)
16805 return true;
16806
16807 OwnedDecl = false;
16809 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
16810 AS, ModulePrivateLoc,
16811 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
16812 TemplateParameterLists.data(), SkipBody);
16813 return Result.get();
16814 } else {
16815 // The "template<>" header is extraneous.
16816 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16817 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16818 isMemberSpecialization = true;
16819 }
16820 }
16821
16822 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
16823 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
16824 return true;
16825 }
16826
16827 // Figure out the underlying type if this a enum declaration. We need to do
16828 // this early, because it's needed to detect if this is an incompatible
16829 // redeclaration.
16830 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
16831 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
16832
16833 if (Kind == TTK_Enum) {
16834 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
16835 // No underlying type explicitly specified, or we failed to parse the
16836 // type, default to int.
16837 EnumUnderlying = Context.IntTy.getTypePtr();
16838 } else if (UnderlyingType.get()) {
16839 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
16840 // integral type; any cv-qualification is ignored.
16841 TypeSourceInfo *TI = nullptr;
16842 GetTypeFromParser(UnderlyingType.get(), &TI);
16843 EnumUnderlying = TI;
16844
16846 // Recover by falling back to int.
16847 EnumUnderlying = Context.IntTy.getTypePtr();
16848
16851 EnumUnderlying = Context.IntTy.getTypePtr();
16852
16853 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
16854 // For MSVC ABI compatibility, unfixed enums must use an underlying type
16855 // of 'int'. However, if this is an unfixed forward declaration, don't set
16856 // the underlying type unless the user enables -fms-compatibility. This
16857 // makes unfixed forward declared enums incomplete and is more conforming.
16858 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
16859 EnumUnderlying = Context.IntTy.getTypePtr();
16860 }
16861 }
16862
16863 DeclContext *SearchDC = CurContext;
16864 DeclContext *DC = CurContext;
16865 bool isStdBadAlloc = false;
16866 bool isStdAlignValT = false;
16867
16869 if (TUK == TUK_Friend || TUK == TUK_Reference)
16870 Redecl = NotForRedeclaration;
16871
16872 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
16873 /// implemented asks for structural equivalence checking, the returned decl
16874 /// here is passed back to the parser, allowing the tag body to be parsed.
16875 auto createTagFromNewDecl = [&]() -> TagDecl * {
16876 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
16877 // If there is an identifier, use the location of the identifier as the
16878 // location of the decl, otherwise use the location of the struct/union
16879 // keyword.
16880 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16881 TagDecl *New = nullptr;
16882
16883 if (Kind == TTK_Enum) {
16884 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
16885 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
16886 // If this is an undefined enum, bail.
16887 if (TUK != TUK_Definition && !Invalid)
16888 return nullptr;
16889 if (EnumUnderlying) {
16890 EnumDecl *ED = cast<EnumDecl>(New);
16891 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
16893 else
16894 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
16895 QualType EnumTy = ED->getIntegerType();
16898 : EnumTy);
16899 }
16900 } else { // struct/union
16901 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16902 nullptr);
16903 }
16904
16905 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16906 // Add alignment attributes if necessary; these attributes are checked
16907 // when the ASTContext lays out the structure.
16908 //
16909 // It is important for implementing the correct semantics that this
16910 // happen here (in ActOnTag). The #pragma pack stack is
16911 // maintained as a result of parser callbacks which can occur at
16912 // many points during the parsing of a struct declaration (because
16913 // the #pragma tokens are effectively skipped over during the
16914 // parsing of the struct).
16915 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16918 }
16919 }
16921 return New;
16922 };
16923
16924 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
16925 if (Name && SS.isNotEmpty()) {
16926 // We have a nested-name tag ('struct foo::bar').
16927
16928 // Check for invalid 'foo::'.
16929 if (SS.isInvalid()) {
16930 Name = nullptr;
16931 goto CreateNewDecl;
16932 }
16933
16934 // If this is a friend or a reference to a class in a dependent
16935 // context, don't try to make a decl for it.
16936 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16937 DC = computeDeclContext(SS, false);
16938 if (!DC) {
16939 IsDependent = true;
16940 return true;
16941 }
16942 } else {
16943 DC = computeDeclContext(SS, true);
16944 if (!DC) {
16945 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16946 << SS.getRange();
16947 return true;
16948 }
16949 }
16950
16951 if (RequireCompleteDeclContext(SS, DC))
16952 return true;
16953
16954 SearchDC = DC;
16955 // Look-up name inside 'foo::'.
16957
16958 if (Previous.isAmbiguous())
16959 return true;
16960
16961 if (Previous.empty()) {
16962 // Name lookup did not find anything. However, if the
16963 // nested-name-specifier refers to the current instantiation,
16964 // and that current instantiation has any dependent base
16965 // classes, we might find something at instantiation time: treat
16966 // this as a dependent elaborated-type-specifier.
16967 // But this only makes any sense for reference-like lookups.
16968 if (Previous.wasNotFoundInCurrentInstantiation() &&
16969 (TUK == TUK_Reference || TUK == TUK_Friend)) {
16970 IsDependent = true;
16971 return true;
16972 }
16973
16974 // A tag 'foo::bar' must already exist.
16975 Diag(NameLoc, diag::err_not_tag_in_scope)
16976 << Kind << Name << DC << SS.getRange();
16977 Name = nullptr;
16978 Invalid = true;
16979 goto CreateNewDecl;
16980 }
16981 } else if (Name) {
16982 // C++14 [class.mem]p14:
16983 // If T is the name of a class, then each of the following shall have a
16984 // name different from T:
16985 // -- every member of class T that is itself a type
16986 if (TUK != TUK_Reference && TUK != TUK_Friend &&
16987 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16988 return true;
16989
16990 // If this is a named struct, check to see if there was a previous forward
16991 // declaration or definition.
16992 // FIXME: We're looking into outer scopes here, even when we
16993 // shouldn't be. Doing so can result in ambiguities that we
16994 // shouldn't be diagnosing.
16995 LookupName(Previous, S);
16996
16997 // When declaring or defining a tag, ignore ambiguities introduced
16998 // by types using'ed into this scope.
16999 if (Previous.isAmbiguous() &&
17000 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17001 LookupResult::Filter F = Previous.makeFilter();
17002 while (F.hasNext()) {
17003 NamedDecl *ND = F.next();
17004 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17005 SearchDC->getRedeclContext()))
17006 F.erase();
17007 }
17008 F.done();
17009 }
17010
17011 // C++11 [namespace.memdef]p3:
17012 // If the name in a friend declaration is neither qualified nor
17013 // a template-id and the declaration is a function or an
17014 // elaborated-type-specifier, the lookup to determine whether
17015 // the entity has been previously declared shall not consider
17016 // any scopes outside the innermost enclosing namespace.
17017 //
17018 // MSVC doesn't implement the above rule for types, so a friend tag
17019 // declaration may be a redeclaration of a type declared in an enclosing
17020 // scope. They do implement this rule for friend functions.
17021 //
17022 // Does it matter that this should be by scope instead of by
17023 // semantic context?
17024 if (!Previous.empty() && TUK == TUK_Friend) {
17025 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17026 LookupResult::Filter F = Previous.makeFilter();
17027 bool FriendSawTagOutsideEnclosingNamespace = false;
17028 while (F.hasNext()) {
17029 NamedDecl *ND = F.next();
17031 if (DC->isFileContext() &&
17032 !EnclosingNS->Encloses(ND->getDeclContext())) {
17033 if (getLangOpts().MSVCCompat)
17034 FriendSawTagOutsideEnclosingNamespace = true;
17035 else
17036 F.erase();
17037 }
17038 }
17039 F.done();
17040
17041 // Diagnose this MSVC extension in the easy case where lookup would have
17042 // unambiguously found something outside the enclosing namespace.
17043 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17044 NamedDecl *ND = Previous.getFoundDecl();
17045 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17046 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17047 }
17048 }
17049
17050 // Note: there used to be some attempt at recovery here.
17051 if (Previous.isAmbiguous())
17052 return true;
17053
17054 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17055 // FIXME: This makes sure that we ignore the contexts associated
17056 // with C structs, unions, and enums when looking for a matching
17057 // tag declaration or definition. See the similar lookup tweak
17058 // in Sema::LookupName; is there a better way to deal with this?
17059 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17060 SearchDC = SearchDC->getParent();
17061 } else if (getLangOpts().CPlusPlus) {
17062 // Inside ObjCContainer want to keep it as a lexical decl context but go
17063 // past it (most often to TranslationUnit) to find the semantic decl
17064 // context.
17065 while (isa<ObjCContainerDecl>(SearchDC))
17066 SearchDC = SearchDC->getParent();
17067 }
17068 } else if (getLangOpts().CPlusPlus) {
17069 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17070 // TagDecl the same way as we skip it for named TagDecl.
17071 while (isa<ObjCContainerDecl>(SearchDC))
17072 SearchDC = SearchDC->getParent();
17073 }
17074
17075 if (Previous.isSingleResult() &&
17076 Previous.getFoundDecl()->isTemplateParameter()) {
17077 // Maybe we will complain about the shadowed template parameter.
17078 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17079 // Just pretend that we didn't see the previous declaration.
17080 Previous.clear();
17081 }
17082
17083 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17084 DC->Equals(getStdNamespace())) {
17085 if (Name->isStr("bad_alloc")) {
17086 // This is a declaration of or a reference to "std::bad_alloc".
17087 isStdBadAlloc = true;
17088
17089 // If std::bad_alloc has been implicitly declared (but made invisible to
17090 // name lookup), fill in this implicit declaration as the previous
17091 // declaration, so that the declarations get chained appropriately.
17092 if (Previous.empty() && StdBadAlloc)
17093 Previous.addDecl(getStdBadAlloc());
17094 } else if (Name->isStr("align_val_t")) {
17095 isStdAlignValT = true;
17096 if (Previous.empty() && StdAlignValT)
17097 Previous.addDecl(getStdAlignValT());
17098 }
17099 }
17100
17101 // If we didn't find a previous declaration, and this is a reference
17102 // (or friend reference), move to the correct scope. In C++, we
17103 // also need to do a redeclaration lookup there, just in case
17104 // there's a shadow friend decl.
17105 if (Name && Previous.empty() &&
17106 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17107 if (Invalid) goto CreateNewDecl;
17108 assert(SS.isEmpty());
17109
17110 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17111 // C++ [basic.scope.pdecl]p5:
17112 // -- for an elaborated-type-specifier of the form
17113 //
17114 // class-key identifier
17115 //
17116 // if the elaborated-type-specifier is used in the
17117 // decl-specifier-seq or parameter-declaration-clause of a
17118 // function defined in namespace scope, the identifier is
17119 // declared as a class-name in the namespace that contains
17120 // the declaration; otherwise, except as a friend
17121 // declaration, the identifier is declared in the smallest
17122 // non-class, non-function-prototype scope that contains the
17123 // declaration.
17124 //
17125 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17126 // C structs and unions.
17127 //
17128 // It is an error in C++ to declare (rather than define) an enum
17129 // type, including via an elaborated type specifier. We'll
17130 // diagnose that later; for now, declare the enum in the same
17131 // scope as we would have picked for any other tag type.
17132 //
17133 // GNU C also supports this behavior as part of its incomplete
17134 // enum types extension, while GNU C++ does not.
17135 //
17136 // Find the context where we'll be declaring the tag.
17137 // FIXME: We would like to maintain the current DeclContext as the
17138 // lexical context,
17139 SearchDC = getTagInjectionContext(SearchDC);
17140
17141 // Find the scope where we'll be declaring the tag.
17143 } else {
17144 assert(TUK == TUK_Friend);
17145 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17146
17147 // C++ [namespace.memdef]p3:
17148 // If a friend declaration in a non-local class first declares a
17149 // class or function, the friend class or function is a member of
17150 // the innermost enclosing namespace.
17151 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17152 : SearchDC->getEnclosingNamespaceContext();
17153 }
17154
17155 // In C++, we need to do a redeclaration lookup to properly
17156 // diagnose some problems.
17157 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17158 // hidden declaration so that we don't get ambiguity errors when using a
17159 // type declared by an elaborated-type-specifier. In C that is not correct
17160 // and we should instead merge compatible types found by lookup.
17161 if (getLangOpts().CPlusPlus) {
17162 // FIXME: This can perform qualified lookups into function contexts,
17163 // which are meaningless.
17164 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17165 LookupQualifiedName(Previous, SearchDC);
17166 } else {
17167 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17168 LookupName(Previous, S);
17169 }
17170 }
17171
17172 // If we have a known previous declaration to use, then use it.
17173 if (Previous.empty() && SkipBody && SkipBody->Previous)
17174 Previous.addDecl(SkipBody->Previous);
17175
17176 if (!Previous.empty()) {
17177 NamedDecl *PrevDecl = Previous.getFoundDecl();
17178 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17179
17180 // It's okay to have a tag decl in the same scope as a typedef
17181 // which hides a tag decl in the same scope. Finding this
17182 // with a redeclaration lookup can only actually happen in C++.
17183 //
17184 // This is also okay for elaborated-type-specifiers, which is
17185 // technically forbidden by the current standard but which is
17186 // okay according to the likely resolution of an open issue;
17187 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17188 if (getLangOpts().CPlusPlus) {
17189 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17190 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17191 TagDecl *Tag = TT->getDecl();
17192 if (Tag->getDeclName() == Name &&
17193 Tag->getDeclContext()->getRedeclContext()
17194 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17195 PrevDecl = Tag;
17196 Previous.clear();
17197 Previous.addDecl(Tag);
17198 Previous.resolveKind();
17199 }
17200 }
17201 }
17202 }
17203
17204 // If this is a redeclaration of a using shadow declaration, it must
17205 // declare a tag in the same context. In MSVC mode, we allow a
17206 // redefinition if either context is within the other.
17207 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17208 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17209 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17210 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17211 !(OldTag && isAcceptableTagRedeclContext(
17212 *this, OldTag->getDeclContext(), SearchDC))) {
17213 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17214 Diag(Shadow->getTargetDecl()->getLocation(),
17215 diag::note_using_decl_target);
17216 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17217 << 0;
17218 // Recover by ignoring the old declaration.
17219 Previous.clear();
17220 goto CreateNewDecl;
17221 }
17222 }
17223
17224 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17225 // If this is a use of a previous tag, or if the tag is already declared
17226 // in the same scope (so that the definition/declaration completes or
17227 // rementions the tag), reuse the decl.
17228 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17229 isDeclInScope(DirectPrevDecl, SearchDC, S,
17230 SS.isNotEmpty() || isMemberSpecialization)) {
17231 // Make sure that this wasn't declared as an enum and now used as a
17232 // struct or something similar.
17233 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17234 TUK == TUK_Definition, KWLoc,
17235 Name)) {
17236 bool SafeToContinue
17237 = (PrevTagDecl->getTagKind() != TTK_Enum &&
17238 Kind != TTK_Enum);
17239 if (SafeToContinue)
17240 Diag(KWLoc, diag::err_use_with_wrong_tag)
17241 << Name
17243 PrevTagDecl->getKindName());
17244 else
17245 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17246 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17247
17248 if (SafeToContinue)
17249 Kind = PrevTagDecl->getTagKind();
17250 else {
17251 // Recover by making this an anonymous redefinition.
17252 Name = nullptr;
17253 Previous.clear();
17254 Invalid = true;
17255 }
17256 }
17257
17258 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
17259 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17260 if (TUK == TUK_Reference || TUK == TUK_Friend)
17261 return PrevTagDecl;
17262
17263 QualType EnumUnderlyingTy;
17264 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17265 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17266 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17267 EnumUnderlyingTy = QualType(T, 0);
17268
17269 // All conflicts with previous declarations are recovered by
17270 // returning the previous declaration, unless this is a definition,
17271 // in which case we want the caller to bail out.
17272 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17273 ScopedEnum, EnumUnderlyingTy,
17274 IsFixed, PrevEnum))
17275 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17276 }
17277
17278 // C++11 [class.mem]p1:
17279 // A member shall not be declared twice in the member-specification,
17280 // except that a nested class or member class template can be declared
17281 // and then later defined.
17282 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17283 S->isDeclScope(PrevDecl)) {
17284 Diag(NameLoc, diag::ext_member_redeclared);
17285 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17286 }
17287
17288 if (!Invalid) {
17289 // If this is a use, just return the declaration we found, unless
17290 // we have attributes.
17291 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17292 if (!Attrs.empty()) {
17293 // FIXME: Diagnose these attributes. For now, we create a new
17294 // declaration to hold them.
17295 } else if (TUK == TUK_Reference &&
17296 (PrevTagDecl->getFriendObjectKind() ==
17298 PrevDecl->getOwningModule() != getCurrentModule()) &&
17299 SS.isEmpty()) {
17300 // This declaration is a reference to an existing entity, but
17301 // has different visibility from that entity: it either makes
17302 // a friend visible or it makes a type visible in a new module.
17303 // In either case, create a new declaration. We only do this if
17304 // the declaration would have meant the same thing if no prior
17305 // declaration were found, that is, if it was found in the same
17306 // scope where we would have injected a declaration.
17307 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17308 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17309 return PrevTagDecl;
17310 // This is in the injected scope, create a new declaration in
17311 // that scope.
17313 } else {
17314 return PrevTagDecl;
17315 }
17316 }
17317
17318 // Diagnose attempts to redefine a tag.
17319 if (TUK == TUK_Definition) {
17320 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17321 // If we're defining a specialization and the previous definition
17322 // is from an implicit instantiation, don't emit an error
17323 // here; we'll catch this in the general case below.
17324 bool IsExplicitSpecializationAfterInstantiation = false;
17325 if (isMemberSpecialization) {
17326 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17327 IsExplicitSpecializationAfterInstantiation =
17328 RD->getTemplateSpecializationKind() !=
17330 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17331 IsExplicitSpecializationAfterInstantiation =
17332 ED->getTemplateSpecializationKind() !=
17334 }
17335
17336 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17337 // not keep more that one definition around (merge them). However,
17338 // ensure the decl passes the structural compatibility check in
17339 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17340 NamedDecl *Hidden = nullptr;
17341 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17342 // There is a definition of this tag, but it is not visible. We
17343 // explicitly make use of C++'s one definition rule here, and
17344 // assume that this definition is identical to the hidden one
17345 // we already have. Make the existing definition visible and
17346 // use it in place of this one.
17347 if (!getLangOpts().CPlusPlus) {
17348 // Postpone making the old definition visible until after we
17349 // complete parsing the new one and do the structural
17350 // comparison.
17351 SkipBody->CheckSameAsPrevious = true;
17352 SkipBody->New = createTagFromNewDecl();
17353 SkipBody->Previous = Def;
17354 return Def;
17355 } else {
17356 SkipBody->ShouldSkip = true;
17357 SkipBody->Previous = Def;
17359 // Carry on and handle it like a normal definition. We'll
17360 // skip starting the definitiion later.
17361 }
17362 } else if (!IsExplicitSpecializationAfterInstantiation) {
17363 // A redeclaration in function prototype scope in C isn't
17364 // visible elsewhere, so merely issue a warning.
17365 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17366 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17367 else
17368 Diag(NameLoc, diag::err_redefinition) << Name;
17370 NameLoc.isValid() ? NameLoc : KWLoc);
17371 // If this is a redefinition, recover by making this
17372 // struct be anonymous, which will make any later
17373 // references get the previous definition.
17374 Name = nullptr;
17375 Previous.clear();
17376 Invalid = true;
17377 }
17378 } else {
17379 // If the type is currently being defined, complain
17380 // about a nested redefinition.
17381 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17382 if (TD->isBeingDefined()) {
17383 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17384 Diag(PrevTagDecl->getLocation(),
17385 diag::note_previous_definition);
17386 Name = nullptr;
17387 Previous.clear();
17388 Invalid = true;
17389 }
17390 }
17391
17392 // Okay, this is definition of a previously declared or referenced
17393 // tag. We're going to create a new Decl for it.
17394 }
17395
17396 // Okay, we're going to make a redeclaration. If this is some kind
17397 // of reference, make sure we build the redeclaration in the same DC
17398 // as the original, and ignore the current access specifier.
17399 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17400 SearchDC = PrevTagDecl->getDeclContext();
17401 AS = AS_none;
17402 }
17403 }
17404 // If we get here we have (another) forward declaration or we
17405 // have a definition. Just create a new decl.
17406
17407 } else {
17408 // If we get here, this is a definition of a new tag type in a nested
17409 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17410 // new decl/type. We set PrevDecl to NULL so that the entities
17411 // have distinct types.
17412 Previous.clear();
17413 }
17414 // If we get here, we're going to create a new Decl. If PrevDecl
17415 // is non-NULL, it's a definition of the tag declared by
17416 // PrevDecl. If it's NULL, we have a new definition.
17417
17418 // Otherwise, PrevDecl is not a tag, but was found with tag
17419 // lookup. This is only actually possible in C++, where a few
17420 // things like templates still live in the tag namespace.
17421 } else {
17422 // Use a better diagnostic if an elaborated-type-specifier
17423 // found the wrong kind of type on the first
17424 // (non-redeclaration) lookup.
17425 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17426 !Previous.isForRedeclaration()) {
17427 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17428 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
17429 << Kind;
17430 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17431 Invalid = true;
17432
17433 // Otherwise, only diagnose if the declaration is in scope.
17434 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17435 SS.isNotEmpty() || isMemberSpecialization)) {
17436 // do nothing
17437
17438 // Diagnose implicit declarations introduced by elaborated types.
17439 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17440 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17441 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17442 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17443 Invalid = true;
17444
17445 // Otherwise it's a declaration. Call out a particularly common
17446 // case here.
17447 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17448 unsigned Kind = 0;
17449 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17450 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17451 << Name << Kind << TND->getUnderlyingType();
17452 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17453 Invalid = true;
17454
17455 // Otherwise, diagnose.
17456 } else {
17457 // The tag name clashes with something else in the target scope,
17458 // issue an error and recover by making this tag be anonymous.
17459 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17460 notePreviousDefinition(PrevDecl, NameLoc);
17461 Name = nullptr;
17462 Invalid = true;
17463 }
17464
17465 // The existing declaration isn't relevant to us; we're in a
17466 // new scope, so clear out the previous declaration.
17467 Previous.clear();
17468 }
17469 }
17470
17471CreateNewDecl:
17472
17473 TagDecl *PrevDecl = nullptr;
17474 if (Previous.isSingleResult())
17475 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17476
17477 // If there is an identifier, use the location of the identifier as the
17478 // location of the decl, otherwise use the location of the struct/union
17479 // keyword.
17480 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17481
17482 // Otherwise, create a new declaration. If there is a previous
17483 // declaration of the same entity, the two will be linked via
17484 // PrevDecl.
17485 TagDecl *New;
17486
17487 if (Kind == TTK_Enum) {
17488 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17489 // enum X { A, B, C } D; D should chain to X.
17490 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17491 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17492 ScopedEnumUsesClassTag, IsFixed);
17493
17494 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17496
17497 // If this is an undefined enum, warn.
17498 if (TUK != TUK_Definition && !Invalid) {
17499 TagDecl *Def;
17500 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17501 // C++0x: 7.2p2: opaque-enum-declaration.
17502 // Conflicts are diagnosed above. Do nothing.
17503 }
17504 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17505 Diag(Loc, diag::ext_forward_ref_enum_def)
17506 << New;
17507 Diag(Def->getLocation(), diag::note_previous_definition);
17508 } else {
17509 unsigned DiagID = diag::ext_forward_ref_enum;
17510 if (getLangOpts().MSVCCompat)
17511 DiagID = diag::ext_ms_forward_ref_enum;
17512 else if (getLangOpts().CPlusPlus)
17513 DiagID = diag::err_forward_ref_enum;
17514 Diag(Loc, DiagID);
17515 }
17516 }
17517
17518 if (EnumUnderlying) {
17519 EnumDecl *ED = cast<EnumDecl>(New);
17520 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17522 else
17523 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17524 QualType EnumTy = ED->getIntegerType();
17527 : EnumTy);
17528 assert(ED->isComplete() && "enum with type should be complete");
17529 }
17530 } else {
17531 // struct/union/class
17532
17533 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17534 // struct X { int A; } D; D should chain to X.
17535 if (getLangOpts().CPlusPlus) {
17536 // FIXME: Look for a way to use RecordDecl for simple structs.
17537 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17538 cast_or_null<CXXRecordDecl>(PrevDecl));
17539
17540 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17542 } else
17543 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17544 cast_or_null<RecordDecl>(PrevDecl));
17545 }
17546
17547 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17548 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17549 << (OOK == OOK_Macro) << New->getSourceRange();
17550
17551 // C++11 [dcl.type]p3:
17552 // A type-specifier-seq shall not define a class or enumeration [...].
17553 if (!Invalid && getLangOpts().CPlusPlus &&
17554 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17555 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17556 << Context.getTagDeclType(New);
17557 Invalid = true;
17558 }
17559
17560 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17561 DC->getDeclKind() == Decl::Enum) {
17562 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17563 << Context.getTagDeclType(New);
17564 Invalid = true;
17565 }
17566
17567 // Maybe add qualifier info.
17568 if (SS.isNotEmpty()) {
17569 if (SS.isSet()) {
17570 // If this is either a declaration or a definition, check the
17571 // nested-name-specifier against the current context.
17572 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17573 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17574 isMemberSpecialization))
17575 Invalid = true;
17576
17578 if (TemplateParameterLists.size() > 0) {
17579 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17580 }
17581 }
17582 else
17583 Invalid = true;
17584 }
17585
17586 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17587 // Add alignment attributes if necessary; these attributes are checked when
17588 // the ASTContext lays out the structure.
17589 //
17590 // It is important for implementing the correct semantics that this
17591 // happen here (in ActOnTag). The #pragma pack stack is
17592 // maintained as a result of parser callbacks which can occur at
17593 // many points during the parsing of a struct declaration (because
17594 // the #pragma tokens are effectively skipped over during the
17595 // parsing of the struct).
17596 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17599 }
17600 }
17601
17602 if (ModulePrivateLoc.isValid()) {
17603 if (isMemberSpecialization)
17604 Diag(New->getLocation(), diag::err_module_private_specialization)
17605 << 2
17606 << FixItHint::CreateRemoval(ModulePrivateLoc);
17607 // __module_private__ does not apply to local classes. However, we only
17608 // diagnose this as an error when the declaration specifiers are
17609 // freestanding. Here, we just ignore the __module_private__.
17610 else if (!SearchDC->isFunctionOrMethod())
17611 New->setModulePrivate();
17612 }
17613
17614 // If this is a specialization of a member class (of a class template),
17615 // check the specialization.
17616 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17617 Invalid = true;
17618
17619 // If we're declaring or defining a tag in function prototype scope in C,
17620 // note that this type can only be used within the function and add it to
17621 // the list of decls to inject into the function definition scope.
17622 if ((Name || Kind == TTK_Enum) &&
17623 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17624 if (getLangOpts().CPlusPlus) {
17625 // C++ [dcl.fct]p6:
17626 // Types shall not be defined in return or parameter types.
17627 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17628 Diag(Loc, diag::err_type_defined_in_param_type)
17629 << Name;
17630 Invalid = true;
17631 }
17632 } else if (!PrevDecl) {
17633 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17634 }
17635 }
17636
17637 if (Invalid)
17638 New->setInvalidDecl();
17639
17640 // Set the lexical context. If the tag has a C++ scope specifier, the
17641 // lexical context will be different from the semantic context.
17643
17644 // Mark this as a friend decl if applicable.
17645 // In Microsoft mode, a friend declaration also acts as a forward
17646 // declaration so we always pass true to setObjectOfFriendDecl to make
17647 // the tag name visible.
17648 if (TUK == TUK_Friend)
17649 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17650
17651 // Set the access specifier.
17652 if (!Invalid && SearchDC->isRecord())
17653 SetMemberAccessSpecifier(New, PrevDecl, AS);
17654
17655 if (PrevDecl)
17656 CheckRedeclarationInModule(New, PrevDecl);
17657
17658 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17659 New->startDefinition();
17660
17661 ProcessDeclAttributeList(S, New, Attrs);
17662 AddPragmaAttributes(S, New);
17663
17664 // If this has an identifier, add it to the scope stack.
17665 if (TUK == TUK_Friend) {
17666 // We might be replacing an existing declaration in the lookup tables;
17667 // if so, borrow its access specifier.
17668 if (PrevDecl)
17669 New->setAccess(PrevDecl->getAccess());
17670
17672 DC->makeDeclVisibleInContext(New);
17673 if (Name) // can be null along some error paths
17674 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17675 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17676 } else if (Name) {
17677 S = getNonFieldDeclScope(S);
17678 PushOnScopeChains(New, S, true);
17679 } else {
17680 CurContext->addDecl(New);
17681 }
17682
17683 // If this is the C FILE type, notify the AST context.
17684 if (IdentifierInfo *II = New->getIdentifier())
17685 if (!New->isInvalidDecl() &&
17687 II->isStr("FILE"))
17688 Context.setFILEDecl(New);
17689
17690 if (PrevDecl)
17691 mergeDeclAttributes(New, PrevDecl);
17692
17693 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
17695
17696 // If there's a #pragma GCC visibility in scope, set the visibility of this
17697 // record.
17699
17700 if (isMemberSpecialization && !New->isInvalidDecl())
17702
17703 OwnedDecl = true;
17704 // In C++, don't return an invalid declaration. We can't recover well from
17705 // the cases where we make the type anonymous.
17706 if (Invalid && getLangOpts().CPlusPlus) {
17707 if (New->isBeingDefined())
17708 if (auto RD = dyn_cast<RecordDecl>(New))
17709 RD->completeDefinition();
17710 return true;
17711 } else if (SkipBody && SkipBody->ShouldSkip) {
17712 return SkipBody->Previous;
17713 } else {
17714 return New;
17715 }
17716}
17717
17720 TagDecl *Tag = cast<TagDecl>(TagD);
17721
17722 // Enter the tag context.
17723 PushDeclContext(S, Tag);
17724
17726
17727 // If there's a #pragma GCC visibility in scope, set the visibility of this
17728 // record.
17730}
17731
17733 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17734 return false;
17735
17736 // Make the previous decl visible.
17738 return true;
17739}
17740
17742 assert(IDecl->getLexicalParent() == CurContext &&
17743 "The next DeclContext should be lexically contained in the current one.");
17744 CurContext = IDecl;
17745}
17746
17748 SourceLocation FinalLoc,
17749 bool IsFinalSpelledSealed,
17750 bool IsAbstract,
17751 SourceLocation LBraceLoc) {
17753 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17754
17755 FieldCollector->StartClass();
17756
17757 if (!Record->getIdentifier())
17758 return;
17759
17760 if (IsAbstract)
17761 Record->markAbstract();
17762
17763 if (FinalLoc.isValid()) {
17764 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
17765 IsFinalSpelledSealed
17766 ? FinalAttr::Keyword_sealed
17767 : FinalAttr::Keyword_final));
17768 }
17769 // C++ [class]p2:
17770 // [...] The class-name is also inserted into the scope of the
17771 // class itself; this is known as the injected-class-name. For
17772 // purposes of access checking, the injected-class-name is treated
17773 // as if it were a public member name.
17774 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
17775 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
17776 Record->getLocation(), Record->getIdentifier(),
17777 /*PrevDecl=*/nullptr,
17778 /*DelayTypeCreation=*/true);
17779 Context.getTypeDeclType(InjectedClassName, Record);
17780 InjectedClassName->setImplicit();
17781 InjectedClassName->setAccess(AS_public);
17782 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
17783 InjectedClassName->setDescribedClassTemplate(Template);
17784 PushOnScopeChains(InjectedClassName, S);
17785 assert(InjectedClassName->isInjectedClassName() &&
17786 "Broken injected-class-name");
17787}
17788
17790 SourceRange BraceRange) {
17792 TagDecl *Tag = cast<TagDecl>(TagD);
17793 Tag->setBraceRange(BraceRange);
17794
17795 // Make sure we "complete" the definition even it is invalid.
17796 if (Tag->isBeingDefined()) {
17797 assert(Tag->isInvalidDecl() && "We should already have completed it");
17798 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17799 RD->completeDefinition();
17800 }
17801
17802 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
17803 FieldCollector->FinishClass();
17804 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
17805 auto *Def = RD->getDefinition();
17806 assert(Def && "The record is expected to have a completed definition");
17807 unsigned NumInitMethods = 0;
17808 for (auto *Method : Def->methods()) {
17809 if (!Method->getIdentifier())
17810 continue;
17811 if (Method->getName() == "__init")
17812 NumInitMethods++;
17813 }
17814 if (NumInitMethods > 1 || !Def->hasInitMethod())
17815 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
17816 }
17817 }
17818
17819 // Exit this scope of this tag's definition.
17821
17822 if (getCurLexicalContext()->isObjCContainer() &&
17823 Tag->getDeclContext()->isFileContext())
17824 Tag->setTopLevelDeclInObjCContainer();
17825
17826 // Notify the consumer that we've defined a tag.
17827 if (!Tag->isInvalidDecl())
17829
17830 // Clangs implementation of #pragma align(packed) differs in bitfield layout
17831 // from XLs and instead matches the XL #pragma pack(1) behavior.
17832 if (Context.getTargetInfo().getTriple().isOSAIX() &&
17833 AlignPackStack.hasValue()) {
17834 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
17835 // Only diagnose #pragma align(packed).
17836 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
17837 return;
17838 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
17839 if (!RD)
17840 return;
17841 // Only warn if there is at least 1 bitfield member.
17842 if (llvm::any_of(RD->fields(),
17843 [](const FieldDecl *FD) { return FD->isBitField(); }))
17844 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
17845 }
17846}
17847
17849 // Exit this scope of this interface definition.
17851}
17852
17854 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
17855 OriginalLexicalContext = ObjCCtx;
17857}
17858
17863
17866 TagDecl *Tag = cast<TagDecl>(TagD);
17867 Tag->setInvalidDecl();
17868
17869 // Make sure we "complete" the definition even it is invalid.
17870 if (Tag->isBeingDefined()) {
17871 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
17872 RD->completeDefinition();
17873 }
17874
17875 // We're undoing ActOnTagStartDefinition here, not
17876 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
17877 // the FieldCollector.
17878
17880}
17881
17882// Note that FieldName may be null for anonymous bitfields.
17884 IdentifierInfo *FieldName, QualType FieldTy,
17885 bool IsMsStruct, Expr *BitWidth) {
17886 assert(BitWidth);
17887 if (BitWidth->containsErrors())
17888 return ExprError();
17889
17890 // C99 6.7.2.1p4 - verify the field type.
17891 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
17892 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
17893 // Handle incomplete and sizeless types with a specific error.
17894 if (RequireCompleteSizedType(FieldLoc, FieldTy,
17895 diag::err_field_incomplete_or_sizeless))
17896 return ExprError();
17897 if (FieldName)
17898 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
17899 << FieldName << FieldTy << BitWidth->getSourceRange();
17900 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
17901 << FieldTy << BitWidth->getSourceRange();
17902 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
17904 return ExprError();
17905
17906 // If the bit-width is type- or value-dependent, don't try to check
17907 // it now.
17908 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
17909 return BitWidth;
17910
17911 llvm::APSInt Value;
17913 if (ICE.isInvalid())
17914 return ICE;
17915 BitWidth = ICE.get();
17916
17917 // Zero-width bitfield is ok for anonymous field.
17918 if (Value == 0 && FieldName)
17919 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
17920
17921 if (Value.isSigned() && Value.isNegative()) {
17922 if (FieldName)
17923 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
17924 << FieldName << toString(Value, 10);
17925 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
17926 << toString(Value, 10);
17927 }
17928
17929 // The size of the bit-field must not exceed our maximum permitted object
17930 // size.
17931 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
17932 return Diag(FieldLoc, diag::err_bitfield_too_wide)
17933 << !FieldName << FieldName << toString(Value, 10);
17934 }
17935
17936 if (!FieldTy->isDependentType()) {
17937 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17938 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17939 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17940
17941 // Over-wide bitfields are an error in C or when using the MSVC bitfield
17942 // ABI.
17943 bool CStdConstraintViolation =
17944 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17945 bool MSBitfieldViolation =
17946 Value.ugt(TypeStorageSize) &&
17947 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17948 if (CStdConstraintViolation || MSBitfieldViolation) {
17949 unsigned DiagWidth =
17950 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17951 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17952 << (bool)FieldName << FieldName << toString(Value, 10)
17953 << !CStdConstraintViolation << DiagWidth;
17954 }
17955
17956 // Warn on types where the user might conceivably expect to get all
17957 // specified bits as value bits: that's all integral types other than
17958 // 'bool'.
17959 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17960 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17961 << FieldName << toString(Value, 10)
17962 << (unsigned)TypeWidth;
17963 }
17964 }
17965
17966 return BitWidth;
17967}
17968
17969/// ActOnField - Each field of a C struct/union is passed into this in order
17970/// to create a FieldDecl object for it.
17972 Declarator &D, Expr *BitfieldWidth) {
17973 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17974 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17975 /*InitStyle=*/ICIS_NoInit, AS_public);
17976 return Res;
17977}
17978
17979/// HandleField - Analyze a field of a C struct or a C++ data member.
17980///
17982 SourceLocation DeclStart,
17983 Declarator &D, Expr *BitWidth,
17984 InClassInitStyle InitStyle,
17985 AccessSpecifier AS) {
17986 if (D.isDecompositionDeclarator()) {
17988 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17989 << Decomp.getSourceRange();
17990 return nullptr;
17991 }
17992
17993 IdentifierInfo *II = D.getIdentifier();
17994 SourceLocation Loc = DeclStart;
17995 if (II) Loc = D.getIdentifierLoc();
17996
17997 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17998 QualType T = TInfo->getType();
17999 if (getLangOpts().CPlusPlus) {
18001
18004 D.setInvalidType();
18005 T = Context.IntTy;
18006 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18007 }
18008 }
18009
18011
18013 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18014 << getLangOpts().CPlusPlus17;
18017 diag::err_invalid_thread)
18019
18020 // Check to see if this name was declared as a member previously
18021 NamedDecl *PrevDecl = nullptr;
18022 LookupResult Previous(*this, II, Loc, LookupMemberName,
18024 LookupName(Previous, S);
18025 switch (Previous.getResultKind()) {
18028 PrevDecl = Previous.getAsSingle<NamedDecl>();
18029 break;
18030
18032 PrevDecl = Previous.getRepresentativeDecl();
18033 break;
18034
18038 break;
18039 }
18040 Previous.suppressDiagnostics();
18041
18042 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18043 // Maybe we will complain about the shadowed template parameter.
18045 // Just pretend that we didn't see the previous declaration.
18046 PrevDecl = nullptr;
18047 }
18048
18049 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18050 PrevDecl = nullptr;
18051
18052 bool Mutable
18053 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18054 SourceLocation TSSL = D.getBeginLoc();
18055 FieldDecl *NewFD
18056 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18057 TSSL, AS, PrevDecl, &D);
18058
18059 if (NewFD->isInvalidDecl())
18060 Record->setInvalidDecl();
18061
18063 NewFD->setModulePrivate();
18064
18065 if (NewFD->isInvalidDecl() && PrevDecl) {
18066 // Don't introduce NewFD into scope; there's already something
18067 // with the same name in the same scope.
18068 } else if (II) {
18069 PushOnScopeChains(NewFD, S);
18070 } else
18071 Record->addDecl(NewFD);
18072
18073 return NewFD;
18074}
18075
18076/// Build a new FieldDecl and check its well-formedness.
18077///
18078/// This routine builds a new FieldDecl given the fields name, type,
18079/// record, etc. \p PrevDecl should refer to any previous declaration
18080/// with the same name and in the same scope as the field to be
18081/// created.
18082///
18083/// \returns a new FieldDecl.
18084///
18085/// \todo The Declarator argument is a hack. It will be removed once
18087 TypeSourceInfo *TInfo,
18088 RecordDecl *Record, SourceLocation Loc,
18089 bool Mutable, Expr *BitWidth,
18090 InClassInitStyle InitStyle,
18091 SourceLocation TSSL,
18092 AccessSpecifier AS, NamedDecl *PrevDecl,
18093 Declarator *D) {
18094 IdentifierInfo *II = Name.getAsIdentifierInfo();
18095 bool InvalidDecl = false;
18096 if (D) InvalidDecl = D->isInvalidType();
18097
18098 // If we receive a broken type, recover by assuming 'int' and
18099 // marking this declaration as invalid.
18100 if (T.isNull() || T->containsErrors()) {
18101 InvalidDecl = true;
18102 T = Context.IntTy;
18103 }
18104
18106 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18107 if (RequireCompleteSizedType(Loc, EltTy,
18108 diag::err_field_incomplete_or_sizeless)) {
18109 // Fields of incomplete type force their record to be invalid.
18110 Record->setInvalidDecl();
18111 InvalidDecl = true;
18112 } else {
18113 NamedDecl *Def;
18114 EltTy->isIncompleteType(&Def);
18115 if (Def && Def->isInvalidDecl()) {
18116 Record->setInvalidDecl();
18117 InvalidDecl = true;
18118 }
18119 }
18120 }
18121
18122 // TR 18037 does not allow fields to be declared with address space
18123 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18124 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18125 Diag(Loc, diag::err_field_with_address_space);
18126 Record->setInvalidDecl();
18127 InvalidDecl = true;
18128 }
18129
18130 if (LangOpts.OpenCL) {
18131 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18132 // used as structure or union field: image, sampler, event or block types.
18133 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18134 T->isBlockPointerType()) {
18135 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18136 Record->setInvalidDecl();
18137 InvalidDecl = true;
18138 }
18139 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18140 // is enabled.
18141 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18142 "__cl_clang_bitfields", LangOpts)) {
18143 Diag(Loc, diag::err_opencl_bitfields);
18144 InvalidDecl = true;
18145 }
18146 }
18147
18148 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18149 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18150 T.hasQualifiers()) {
18151 InvalidDecl = true;
18152 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18153 }
18154
18155 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18156 // than a variably modified type.
18157 if (!InvalidDecl && T->isVariablyModifiedType()) {
18159 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18160 InvalidDecl = true;
18161 }
18162
18163 // Fields can not have abstract class types
18164 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18165 diag::err_abstract_type_in_decl,
18167 InvalidDecl = true;
18168
18169 if (InvalidDecl)
18170 BitWidth = nullptr;
18171 // If this is declared as a bit-field, check the bit-field.
18172 if (BitWidth) {
18173 BitWidth =
18174 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18175 if (!BitWidth) {
18176 InvalidDecl = true;
18177 BitWidth = nullptr;
18178 }
18179 }
18180
18181 // Check that 'mutable' is consistent with the type of the declaration.
18182 if (!InvalidDecl && Mutable) {
18183 unsigned DiagID = 0;
18184 if (T->isReferenceType())
18185 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18186 : diag::err_mutable_reference;
18187 else if (T.isConstQualified())
18188 DiagID = diag::err_mutable_const;
18189
18190 if (DiagID) {
18191 SourceLocation ErrLoc = Loc;
18192 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18193 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18194 Diag(ErrLoc, DiagID);
18195 if (DiagID != diag::ext_mutable_reference) {
18196 Mutable = false;
18197 InvalidDecl = true;
18198 }
18199 }
18200 }
18201
18202 // C++11 [class.union]p8 (DR1460):
18203 // At most one variant member of a union may have a
18204 // brace-or-equal-initializer.
18205 if (InitStyle != ICIS_NoInit)
18206 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18207
18208 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18209 BitWidth, Mutable, InitStyle);
18210 if (InvalidDecl)
18211 NewFD->setInvalidDecl();
18212
18213 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
18214 Diag(Loc, diag::err_duplicate_member) << II;
18215 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18216 NewFD->setInvalidDecl();
18217 }
18218
18219 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18220 if (Record->isUnion()) {
18221 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18222 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18223 if (RDecl->getDefinition()) {
18224 // C++ [class.union]p1: An object of a class with a non-trivial
18225 // constructor, a non-trivial copy constructor, a non-trivial
18226 // destructor, or a non-trivial copy assignment operator
18227 // cannot be a member of a union, nor can an array of such
18228 // objects.
18229 if (CheckNontrivialField(NewFD))
18230 NewFD->setInvalidDecl();
18231 }
18232 }
18233
18234 // C++ [class.union]p1: If a union contains a member of reference type,
18235 // the program is ill-formed, except when compiling with MSVC extensions
18236 // enabled.
18237 if (EltTy->isReferenceType()) {
18238 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18239 diag::ext_union_member_of_reference_type :
18240 diag::err_union_member_of_reference_type)
18241 << NewFD->getDeclName() << EltTy;
18242 if (!getLangOpts().MicrosoftExt)
18243 NewFD->setInvalidDecl();
18244 }
18245 }
18246 }
18247
18248 // FIXME: We need to pass in the attributes given an AST
18249 // representation, not a parser representation.
18250 if (D) {
18251 // FIXME: The current scope is almost... but not entirely... correct here.
18252 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18253
18254 if (NewFD->hasAttrs())
18256 }
18257
18258 // In auto-retain/release, infer strong retension for fields of
18259 // retainable type.
18260 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18261 NewFD->setInvalidDecl();
18262
18263 if (T.isObjCGCWeak())
18264 Diag(Loc, diag::warn_attribute_weak_on_field);
18265
18266 // PPC MMA non-pointer types are not allowed as field types.
18267 if (Context.getTargetInfo().getTriple().isPPC64() &&
18268 CheckPPCMMAType(T, NewFD->getLocation()))
18269 NewFD->setInvalidDecl();
18270
18271 NewFD->setAccess(AS);
18272 return NewFD;
18273}
18274
18276 assert(FD);
18277 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18278
18279 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18280 return false;
18281
18283 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18284 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18285 if (RDecl->getDefinition()) {
18286 // We check for copy constructors before constructors
18287 // because otherwise we'll never get complaints about
18288 // copy constructors.
18289
18291 // We're required to check for any non-trivial constructors. Since the
18292 // implicit default constructor is suppressed if there are any
18293 // user-declared constructors, we just need to check that there is a
18294 // trivial default constructor and a trivial copy constructor. (We don't
18295 // worry about move constructors here, since this is a C++98 check.)
18296 if (RDecl->hasNonTrivialCopyConstructor())
18297 member = CXXCopyConstructor;
18298 else if (!RDecl->hasTrivialDefaultConstructor())
18299 member = CXXDefaultConstructor;
18300 else if (RDecl->hasNonTrivialCopyAssignment())
18301 member = CXXCopyAssignment;
18302 else if (RDecl->hasNonTrivialDestructor())
18303 member = CXXDestructor;
18304
18305 if (member != CXXInvalid) {
18306 if (!getLangOpts().CPlusPlus11 &&
18307 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18308 // Objective-C++ ARC: it is an error to have a non-trivial field of
18309 // a union. However, system headers in Objective-C programs
18310 // occasionally have Objective-C lifetime objects within unions,
18311 // and rather than cause the program to fail, we make those
18312 // members unavailable.
18313 SourceLocation Loc = FD->getLocation();
18314 if (getSourceManager().isInSystemHeader(Loc)) {
18315 if (!FD->hasAttr<UnavailableAttr>())
18316 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18317 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18318 return false;
18319 }
18320 }
18321
18323 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18324 diag::err_illegal_union_or_anon_struct_member)
18325 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18326 DiagnoseNontrivial(RDecl, member);
18327 return !getLangOpts().CPlusPlus11;
18328 }
18329 }
18330 }
18331
18332 return false;
18333}
18334
18335/// TranslateIvarVisibility - Translate visibility from a token ID to an
18336/// AST enum value.
18339 switch (ivarVisibility) {
18340 default: llvm_unreachable("Unknown visitibility kind");
18341 case tok::objc_private: return ObjCIvarDecl::Private;
18342 case tok::objc_public: return ObjCIvarDecl::Public;
18343 case tok::objc_protected: return ObjCIvarDecl::Protected;
18344 case tok::objc_package: return ObjCIvarDecl::Package;
18345 }
18346}
18347
18348/// ActOnIvar - Each ivar field of an objective-c class is passed into this
18349/// in order to create an IvarDecl object for it.
18351 SourceLocation DeclStart,
18352 Declarator &D, Expr *BitfieldWidth,
18354
18355 IdentifierInfo *II = D.getIdentifier();
18356 Expr *BitWidth = (Expr*)BitfieldWidth;
18357 SourceLocation Loc = DeclStart;
18358 if (II) Loc = D.getIdentifierLoc();
18359
18360 // FIXME: Unnamed fields can be handled in various different ways, for
18361 // example, unnamed unions inject all members into the struct namespace!
18362
18363 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18364 QualType T = TInfo->getType();
18365
18366 if (BitWidth) {
18367 // 6.7.2.1p3, 6.7.2.1p4
18368 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18369 if (!BitWidth)
18370 D.setInvalidType();
18371 } else {
18372 // Not a bitfield.
18373
18374 // validate II.
18375
18376 }
18377 if (T->isReferenceType()) {
18378 Diag(Loc, diag::err_ivar_reference_type);
18379 D.setInvalidType();
18380 }
18381 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18382 // than a variably modified type.
18383 else if (T->isVariablyModifiedType()) {
18385 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18386 D.setInvalidType();
18387 }
18388
18389 // Get the visibility (access control) for this ivar.
18391 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18393 // Must set ivar's DeclContext to its enclosing interface.
18395 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18396 return nullptr;
18397 ObjCContainerDecl *EnclosingContext;
18398 if (ObjCImplementationDecl *IMPDecl =
18399 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18401 // Case of ivar declared in an implementation. Context is that of its class.
18402 EnclosingContext = IMPDecl->getClassInterface();
18403 assert(EnclosingContext && "Implementation has no class interface!");
18404 }
18405 else
18406 EnclosingContext = EnclosingDecl;
18407 } else {
18408 if (ObjCCategoryDecl *CDecl =
18409 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18410 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18411 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18412 return nullptr;
18413 }
18414 }
18415 EnclosingContext = EnclosingDecl;
18416 }
18417
18418 // Construct the decl.
18419 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
18420 DeclStart, Loc, II, T,
18421 TInfo, ac, (Expr *)BitfieldWidth);
18422
18423 if (II) {
18424 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18426 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18427 && !isa<TagDecl>(PrevDecl)) {
18428 Diag(Loc, diag::err_duplicate_member) << II;
18429 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18430 NewID->setInvalidDecl();
18431 }
18432 }
18433
18434 // Process attributes attached to the ivar.
18435 ProcessDeclAttributes(S, NewID, D);
18436
18437 if (D.isInvalidType())
18438 NewID->setInvalidDecl();
18439
18440 // In ARC, infer 'retaining' for ivars of retainable type.
18441 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18442 NewID->setInvalidDecl();
18443
18445 NewID->setModulePrivate();
18446
18447 if (II) {
18448 // FIXME: When interfaces are DeclContexts, we'll need to add
18449 // these to the interface.
18450 S->AddDecl(NewID);
18451 IdResolver.AddDecl(NewID);
18452 }
18453
18455 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18456 Diag(Loc, diag::warn_ivars_in_interface);
18457
18458 return NewID;
18459}
18460
18461/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18462/// class and class extensions. For every class \@interface and class
18463/// extension \@interface, if the last ivar is a bitfield of any type,
18464/// then add an implicit `char :0` ivar to the end of that interface.
18466 SmallVectorImpl<Decl *> &AllIvarDecls) {
18467 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18468 return;
18469
18470 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18471 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18472
18473 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18474 return;
18475 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18476 if (!ID) {
18477 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18478 if (!CD->IsClassExtension())
18479 return;
18480 }
18481 // No need to add this to end of @implementation.
18482 else
18483 return;
18484 }
18485 // All conditions are met. Add a new bitfield to the tail end of ivars.
18486 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18487 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18488
18489 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18490 DeclLoc, DeclLoc, nullptr,
18493 DeclLoc),
18495 true);
18496 AllIvarDecls.push_back(Ivar);
18497}
18498
18499/// [class.dtor]p4:
18500/// At the end of the definition of a class, overload resolution is
18501/// performed among the prospective destructors declared in that class with
18502/// an empty argument list to select the destructor for the class, also
18503/// known as the selected destructor.
18504///
18505/// We do the overload resolution here, then mark the selected constructor in the AST.
18506/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18508 if (!Record->hasUserDeclaredDestructor()) {
18509 return;
18510 }
18511
18512 SourceLocation Loc = Record->getLocation();
18514
18515 for (auto *Decl : Record->decls()) {
18516 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18517 if (DD->isInvalidDecl())
18518 continue;
18519 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18520 OCS);
18521 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18522 }
18523 }
18524
18525 if (OCS.empty()) {
18526 return;
18527 }
18529 unsigned Msg = 0;
18530 OverloadCandidateDisplayKind DisplayKind;
18531
18532 switch (OCS.BestViableFunction(S, Loc, Best)) {
18533 case OR_Success:
18534 case OR_Deleted:
18535 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18536 break;
18537
18538 case OR_Ambiguous:
18539 Msg = diag::err_ambiguous_destructor;
18540 DisplayKind = OCD_AmbiguousCandidates;
18541 break;
18542
18544 Msg = diag::err_no_viable_destructor;
18545 DisplayKind = OCD_AllCandidates;
18546 break;
18547 }
18548
18549 if (Msg) {
18550 // OpenCL have got their own thing going with destructors. It's slightly broken,
18551 // but we allow it.
18552 if (!S.LangOpts.OpenCL) {
18553 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18554 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18555 Record->setInvalidDecl();
18556 }
18557 // It's a bit hacky: At this point we've raised an error but we want the
18558 // rest of the compiler to continue somehow working. However almost
18559 // everything we'll try to do with the class will depend on there being a
18560 // destructor. So let's pretend the first one is selected and hope for the
18561 // best.
18562 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18563 }
18564}
18565
18566/// [class.mem.special]p5
18567/// Two special member functions are of the same kind if:
18568/// - they are both default constructors,
18569/// - they are both copy or move constructors with the same first parameter
18570/// type, or
18571/// - they are both copy or move assignment operators with the same first
18572/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18574 CXXMethodDecl *M1,
18575 CXXMethodDecl *M2,
18577 // We don't want to compare templates to non-templates: See
18578 // https://github.com/llvm/llvm-project/issues/59206
18579 if (CSM == Sema::CXXDefaultConstructor)
18580 return bool(M1->getDescribedFunctionTemplate()) ==
18582 if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
18583 M2->getParamDecl(0)->getType()))
18584 return false;
18585 if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
18586 return false;
18587
18588 return true;
18589}
18590
18591/// [class.mem.special]p6:
18592/// An eligible special member function is a special member function for which:
18593/// - the function is not deleted,
18594/// - the associated constraints, if any, are satisfied, and
18595/// - no special member function of the same kind whose associated constraints
18596/// [CWG2595], if any, are satisfied is more constrained.
18597static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18600 SmallVector<bool, 4> SatisfactionStatus;
18601
18602 for (CXXMethodDecl *Method : Methods) {
18603 const Expr *Constraints = Method->getTrailingRequiresClause();
18604 if (!Constraints)
18605 SatisfactionStatus.push_back(true);
18606 else {
18607 ConstraintSatisfaction Satisfaction;
18608 if (S.CheckFunctionConstraints(Method, Satisfaction))
18609 SatisfactionStatus.push_back(false);
18610 else
18611 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18612 }
18613 }
18614
18615 for (size_t i = 0; i < Methods.size(); i++) {
18616 if (!SatisfactionStatus[i])
18617 continue;
18618 CXXMethodDecl *Method = Methods[i];
18619 CXXMethodDecl *OrigMethod = Method;
18620 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18621 OrigMethod = cast<CXXMethodDecl>(MF);
18622
18623 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18624 bool AnotherMethodIsMoreConstrained = false;
18625 for (size_t j = 0; j < Methods.size(); j++) {
18626 if (i == j || !SatisfactionStatus[j])
18627 continue;
18628 CXXMethodDecl *OtherMethod = Methods[j];
18629 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18630 OtherMethod = cast<CXXMethodDecl>(MF);
18631
18632 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18633 CSM))
18634 continue;
18635
18636 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18637 if (!OtherConstraints)
18638 continue;
18639 if (!Constraints) {
18640 AnotherMethodIsMoreConstrained = true;
18641 break;
18642 }
18643 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18644 {Constraints},
18645 AnotherMethodIsMoreConstrained)) {
18646 // There was an error with the constraints comparison. Exit the loop
18647 // and don't consider this function eligible.
18648 AnotherMethodIsMoreConstrained = true;
18649 }
18650 if (AnotherMethodIsMoreConstrained)
18651 break;
18652 }
18653 // FIXME: Do not consider deleted methods as eligible after implementing
18654 // DR1734 and DR1496.
18655 if (!AnotherMethodIsMoreConstrained) {
18656 Method->setIneligibleOrNotSelected(false);
18657 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18658 }
18659 }
18660}
18661
18663 CXXRecordDecl *Record) {
18664 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18665 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18666 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18667 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18668 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18669
18670 for (auto *Decl : Record->decls()) {
18671 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18672 if (!MD) {
18673 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18674 if (FTD)
18675 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18676 }
18677 if (!MD)
18678 continue;
18679 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18680 if (CD->isInvalidDecl())
18681 continue;
18682 if (CD->isDefaultConstructor())
18683 DefaultConstructors.push_back(MD);
18684 else if (CD->isCopyConstructor())
18685 CopyConstructors.push_back(MD);
18686 else if (CD->isMoveConstructor())
18687 MoveConstructors.push_back(MD);
18688 } else if (MD->isCopyAssignmentOperator()) {
18689 CopyAssignmentOperators.push_back(MD);
18690 } else if (MD->isMoveAssignmentOperator()) {
18691 MoveAssignmentOperators.push_back(MD);
18692 }
18693 }
18694
18695 SetEligibleMethods(S, Record, DefaultConstructors,
18697 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
18698 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
18699 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18701 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18703}
18704
18705void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18706 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18707 SourceLocation RBrac,
18708 const ParsedAttributesView &Attrs) {
18709 assert(EnclosingDecl && "missing record or interface decl");
18710
18711 // If this is an Objective-C @implementation or category and we have
18712 // new fields here we should reset the layout of the interface since
18713 // it will now change.
18714 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18715 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18716 switch (DC->getKind()) {
18717 default: break;
18718 case Decl::ObjCCategory:
18719 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18720 break;
18721 case Decl::ObjCImplementation:
18722 Context.
18723 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18724 break;
18725 }
18726 }
18727
18728 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18729 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18730
18731 // Start counting up the number of named members; make sure to include
18732 // members of anonymous structs and unions in the total.
18733 unsigned NumNamedMembers = 0;
18734 if (Record) {
18735 for (const auto *I : Record->decls()) {
18736 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18737 if (IFD->getDeclName())
18738 ++NumNamedMembers;
18739 }
18740 }
18741
18742 // Verify that all the fields are okay.
18744
18745 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18746 i != end; ++i) {
18747 FieldDecl *FD = cast<FieldDecl>(*i);
18748
18749 // Get the type for the field.
18750 const Type *FDTy = FD->getType().getTypePtr();
18751
18752 if (!FD->isAnonymousStructOrUnion()) {
18753 // Remember all fields written by the user.
18754 RecFields.push_back(FD);
18755 }
18756
18757 // If the field is already invalid for some reason, don't emit more
18758 // diagnostics about it.
18759 if (FD->isInvalidDecl()) {
18760 EnclosingDecl->setInvalidDecl();
18761 continue;
18762 }
18763
18764 // C99 6.7.2.1p2:
18765 // A structure or union shall not contain a member with
18766 // incomplete or function type (hence, a structure shall not
18767 // contain an instance of itself, but may contain a pointer to
18768 // an instance of itself), except that the last member of a
18769 // structure with more than one named member may have incomplete
18770 // array type; such a structure (and any union containing,
18771 // possibly recursively, a member that is such a structure)
18772 // shall not be a member of a structure or an element of an
18773 // array.
18774 bool IsLastField = (i + 1 == Fields.end());
18775 if (FDTy->isFunctionType()) {
18776 // Field declared as a function.
18777 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18778 << FD->getDeclName();
18779 FD->setInvalidDecl();
18780 EnclosingDecl->setInvalidDecl();
18781 continue;
18782 } else if (FDTy->isIncompleteArrayType() &&
18783 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18784 if (Record) {
18785 // Flexible array member.
18786 // Microsoft and g++ is more permissive regarding flexible array.
18787 // It will accept flexible array in union and also
18788 // as the sole element of a struct/class.
18789 unsigned DiagID = 0;
18790 if (!Record->isUnion() && !IsLastField) {
18791 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18792 << FD->getDeclName() << FD->getType() << Record->getTagKind();
18793 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18794 FD->setInvalidDecl();
18795 EnclosingDecl->setInvalidDecl();
18796 continue;
18797 } else if (Record->isUnion())
18798 DiagID = getLangOpts().MicrosoftExt
18799 ? diag::ext_flexible_array_union_ms
18800 : getLangOpts().CPlusPlus
18801 ? diag::ext_flexible_array_union_gnu
18802 : diag::err_flexible_array_union;
18803 else if (NumNamedMembers < 1)
18804 DiagID = getLangOpts().MicrosoftExt
18805 ? diag::ext_flexible_array_empty_aggregate_ms
18806 : getLangOpts().CPlusPlus
18807 ? diag::ext_flexible_array_empty_aggregate_gnu
18808 : diag::err_flexible_array_empty_aggregate;
18809
18810 if (DiagID)
18811 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
18812 << Record->getTagKind();
18813 // While the layout of types that contain virtual bases is not specified
18814 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18815 // virtual bases after the derived members. This would make a flexible
18816 // array member declared at the end of an object not adjacent to the end
18817 // of the type.
18818 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18819 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18820 << FD->getDeclName() << Record->getTagKind();
18821 if (!getLangOpts().C99)
18822 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18823 << FD->getDeclName() << Record->getTagKind();
18824
18825 // If the element type has a non-trivial destructor, we would not
18826 // implicitly destroy the elements, so disallow it for now.
18827 //
18828 // FIXME: GCC allows this. We should probably either implicitly delete
18829 // the destructor of the containing class, or just allow this.
18830 QualType BaseElem = Context.getBaseElementType(FD->getType());
18831 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18832 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18833 << FD->getDeclName() << FD->getType();
18834 FD->setInvalidDecl();
18835 EnclosingDecl->setInvalidDecl();
18836 continue;
18837 }
18838 // Okay, we have a legal flexible array member at the end of the struct.
18839 Record->setHasFlexibleArrayMember(true);
18840 } else {
18841 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18842 // unless they are followed by another ivar. That check is done
18843 // elsewhere, after synthesized ivars are known.
18844 }
18845 } else if (!FDTy->isDependentType() &&
18847 FD->getLocation(), FD->getType(),
18848 diag::err_field_incomplete_or_sizeless)) {
18849 // Incomplete type
18850 FD->setInvalidDecl();
18851 EnclosingDecl->setInvalidDecl();
18852 continue;
18853 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18854 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18855 // A type which contains a flexible array member is considered to be a
18856 // flexible array member.
18857 Record->setHasFlexibleArrayMember(true);
18858 if (!Record->isUnion()) {
18859 // If this is a struct/class and this is not the last element, reject
18860 // it. Note that GCC supports variable sized arrays in the middle of
18861 // structures.
18862 if (!IsLastField)
18863 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18864 << FD->getDeclName() << FD->getType();
18865 else {
18866 // We support flexible arrays at the end of structs in
18867 // other structs as an extension.
18868 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18869 << FD->getDeclName();
18870 }
18871 }
18872 }
18873 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18875 diag::err_abstract_type_in_decl,
18877 // Ivars can not have abstract class types
18878 FD->setInvalidDecl();
18879 }
18880 if (Record && FDTTy->getDecl()->hasObjectMember())
18881 Record->setHasObjectMember(true);
18882 if (Record && FDTTy->getDecl()->hasVolatileMember())
18883 Record->setHasVolatileMember(true);
18884 } else if (FDTy->isObjCObjectType()) {
18885 /// A field cannot be an Objective-c object
18886 Diag(FD->getLocation(), diag::err_statically_allocated_object)
18889 FD->setType(T);
18890 } else if (Record && Record->isUnion() &&
18892 getSourceManager().isInSystemHeader(FD->getLocation()) &&
18893 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18896 // For backward compatibility, fields of C unions declared in system
18897 // headers that have non-trivial ObjC ownership qualifications are marked
18898 // as unavailable unless the qualifier is explicit and __strong. This can
18899 // break ABI compatibility between programs compiled with ARC and MRR, but
18900 // is a better option than rejecting programs using those unions under
18901 // ARC.
18902 FD->addAttr(UnavailableAttr::CreateImplicit(
18903 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18904 FD->getLocation()));
18905 } else if (getLangOpts().ObjC &&
18906 getLangOpts().getGC() != LangOptions::NonGC && Record &&
18907 !Record->hasObjectMember()) {
18908 if (FD->getType()->isObjCObjectPointerType() ||
18909 FD->getType().isObjCGCStrong())
18910 Record->setHasObjectMember(true);
18911 else if (Context.getAsArrayType(FD->getType())) {
18912 QualType BaseType = Context.getBaseElementType(FD->getType());
18913 if (BaseType->isRecordType() &&
18914 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
18915 Record->setHasObjectMember(true);
18916 else if (BaseType->isObjCObjectPointerType() ||
18917 BaseType.isObjCGCStrong())
18918 Record->setHasObjectMember(true);
18919 }
18920 }
18921
18922 if (Record && !getLangOpts().CPlusPlus &&
18923 !shouldIgnoreForRecordTriviality(FD)) {
18924 QualType FT = FD->getType();
18926 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
18928 Record->isUnion())
18929 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
18930 }
18933 Record->setNonTrivialToPrimitiveCopy(true);
18934 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
18935 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
18936 }
18937 if (FT.isDestructedType()) {
18938 Record->setNonTrivialToPrimitiveDestroy(true);
18939 Record->setParamDestroyedInCallee(true);
18940 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
18941 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
18942 }
18943
18944 if (const auto *RT = FT->getAs<RecordType>()) {
18945 if (RT->getDecl()->getArgPassingRestrictions() ==
18947 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18949 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
18950 }
18951
18952 if (Record && FD->getType().isVolatileQualified())
18953 Record->setHasVolatileMember(true);
18954 // Keep track of the number of named members.
18955 if (FD->getIdentifier())
18956 ++NumNamedMembers;
18957 }
18958
18959 // Okay, we successfully defined 'Record'.
18960 if (Record) {
18961 bool Completed = false;
18962 if (CXXRecord) {
18963 if (!CXXRecord->isInvalidDecl()) {
18964 // Set access bits correctly on the directly-declared conversions.
18966 I = CXXRecord->conversion_begin(),
18967 E = CXXRecord->conversion_end(); I != E; ++I)
18968 I.setAccess((*I)->getAccess());
18969 }
18970
18971 // Add any implicitly-declared members to this class.
18973
18974 if (!CXXRecord->isDependentType()) {
18975 if (!CXXRecord->isInvalidDecl()) {
18976 // If we have virtual base classes, we may end up finding multiple
18977 // final overriders for a given virtual function. Check for this
18978 // problem now.
18979 if (CXXRecord->getNumVBases()) {
18980 CXXFinalOverriderMap FinalOverriders;
18981 CXXRecord->getFinalOverriders(FinalOverriders);
18982
18983 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
18984 MEnd = FinalOverriders.end();
18985 M != MEnd; ++M) {
18986 for (OverridingMethods::iterator SO = M->second.begin(),
18987 SOEnd = M->second.end();
18988 SO != SOEnd; ++SO) {
18989 assert(SO->second.size() > 0 &&
18990 "Virtual function without overriding functions?");
18991 if (SO->second.size() == 1)
18992 continue;
18993
18994 // C++ [class.virtual]p2:
18995 // In a derived class, if a virtual member function of a base
18996 // class subobject has more than one final overrider the
18997 // program is ill-formed.
18998 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
18999 << (const NamedDecl *)M->first << Record;
19000 Diag(M->first->getLocation(),
19001 diag::note_overridden_virtual_function);
19003 OM = SO->second.begin(),
19004 OMEnd = SO->second.end();
19005 OM != OMEnd; ++OM)
19006 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19007 << (const NamedDecl *)M->first << OM->Method->getParent();
19008
19009 Record->setInvalidDecl();
19010 }
19011 }
19012 CXXRecord->completeDefinition(&FinalOverriders);
19013 Completed = true;
19014 }
19015 }
19016 ComputeSelectedDestructor(*this, CXXRecord);
19018 }
19019 }
19020
19021 if (!Completed)
19022 Record->completeDefinition();
19023
19024 // Handle attributes before checking the layout.
19025 ProcessDeclAttributeList(S, Record, Attrs);
19026
19027 // Check to see if a FieldDecl is a pointer to a function.
19028 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19029 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19030 if (!FD) {
19031 // Check whether this is a forward declaration that was inserted by
19032 // Clang. This happens when a non-forward declared / defined type is
19033 // used, e.g.:
19034 //
19035 // struct foo {
19036 // struct bar *(*f)();
19037 // struct bar *(*g)();
19038 // };
19039 //
19040 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19041 // incomplete definition.
19042 if (const auto *TD = dyn_cast<TagDecl>(D))
19043 return !TD->isCompleteDefinition();
19044 return false;
19045 }
19046 QualType FieldType = FD->getType().getDesugaredType(Context);
19047 if (isa<PointerType>(FieldType)) {
19048 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19049 return PointeeType.getDesugaredType(Context)->isFunctionType();
19050 }
19051 return false;
19052 };
19053
19054 // Maybe randomize the record's decls. We automatically randomize a record
19055 // of function pointers, unless it has the "no_randomize_layout" attribute.
19056 if (!getLangOpts().CPlusPlus &&
19057 (Record->hasAttr<RandomizeLayoutAttr>() ||
19058 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19059 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19060 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19061 !Record->isRandomized()) {
19062 SmallVector<Decl *, 32> NewDeclOrdering;
19064 NewDeclOrdering))
19065 Record->reorderDecls(NewDeclOrdering);
19066 }
19067
19068 // We may have deferred checking for a deleted destructor. Check now.
19069 if (CXXRecord) {
19070 auto *Dtor = CXXRecord->getDestructor();
19071 if (Dtor && Dtor->isImplicit() &&
19073 CXXRecord->setImplicitDestructorIsDeleted();
19074 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19075 }
19076 }
19077
19078 if (Record->hasAttrs()) {
19080
19081 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19082 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19083 IA->getRange(), IA->getBestCase(),
19084 IA->getInheritanceModel());
19085 }
19086
19087 // Check if the structure/union declaration is a type that can have zero
19088 // size in C. For C this is a language extension, for C++ it may cause
19089 // compatibility problems.
19090 bool CheckForZeroSize;
19091 if (!getLangOpts().CPlusPlus) {
19092 CheckForZeroSize = true;
19093 } else {
19094 // For C++ filter out types that cannot be referenced in C code.
19095 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19096 CheckForZeroSize =
19097 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19098 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19099 CXXRecord->isCLike();
19100 }
19101 if (CheckForZeroSize) {
19102 bool ZeroSize = true;
19103 bool IsEmpty = true;
19104 unsigned NonBitFields = 0;
19105 for (RecordDecl::field_iterator I = Record->field_begin(),
19106 E = Record->field_end();
19107 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19108 IsEmpty = false;
19109 if (I->isUnnamedBitfield()) {
19110 if (!I->isZeroLengthBitField(Context))
19111 ZeroSize = false;
19112 } else {
19113 ++NonBitFields;
19114 QualType FieldType = I->getType();
19115 if (FieldType->isIncompleteType() ||
19116 !Context.getTypeSizeInChars(FieldType).isZero())
19117 ZeroSize = false;
19118 }
19119 }
19120
19121 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19122 // allowed in C++, but warn if its declaration is inside
19123 // extern "C" block.
19124 if (ZeroSize) {
19125 Diag(RecLoc, getLangOpts().CPlusPlus ?
19126 diag::warn_zero_size_struct_union_in_extern_c :
19127 diag::warn_zero_size_struct_union_compat)
19128 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19129 }
19130
19131 // Structs without named members are extension in C (C99 6.7.2.1p7),
19132 // but are accepted by GCC.
19133 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19134 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19135 diag::ext_no_named_members_in_struct_union)
19136 << Record->isUnion();
19137 }
19138 }
19139 } else {
19140 ObjCIvarDecl **ClsFields =
19141 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19142 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19143 ID->setEndOfDefinitionLoc(RBrac);
19144 // Add ivar's to class's DeclContext.
19145 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19146 ClsFields[i]->setLexicalDeclContext(ID);
19147 ID->addDecl(ClsFields[i]);
19148 }
19149 // Must enforce the rule that ivars in the base classes may not be
19150 // duplicates.
19151 if (ID->getSuperClass())
19152 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19153 } else if (ObjCImplementationDecl *IMPDecl =
19154 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19155 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19156 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19157 // Ivar declared in @implementation never belongs to the implementation.
19158 // Only it is in implementation's lexical context.
19159 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19160 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19161 IMPDecl->setIvarLBraceLoc(LBrac);
19162 IMPDecl->setIvarRBraceLoc(RBrac);
19163 } else if (ObjCCategoryDecl *CDecl =
19164 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19165 // case of ivars in class extension; all other cases have been
19166 // reported as errors elsewhere.
19167 // FIXME. Class extension does not have a LocEnd field.
19168 // CDecl->setLocEnd(RBrac);
19169 // Add ivar's to class extension's DeclContext.
19170 // Diagnose redeclaration of private ivars.
19171 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19172 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19173 if (IDecl) {
19174 if (const ObjCIvarDecl *ClsIvar =
19175 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19176 Diag(ClsFields[i]->getLocation(),
19177 diag::err_duplicate_ivar_declaration);
19178 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19179 continue;
19180 }
19181 for (const auto *Ext : IDecl->known_extensions()) {
19182 if (const ObjCIvarDecl *ClsExtIvar
19183 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19184 Diag(ClsFields[i]->getLocation(),
19185 diag::err_duplicate_ivar_declaration);
19186 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19187 continue;
19188 }
19189 }
19190 }
19191 ClsFields[i]->setLexicalDeclContext(CDecl);
19192 CDecl->addDecl(ClsFields[i]);
19193 }
19194 CDecl->setIvarLBraceLoc(LBrac);
19195 CDecl->setIvarRBraceLoc(RBrac);
19196 }
19197 }
19198}
19199
19200/// Determine whether the given integral value is representable within
19201/// the given type T.
19203 llvm::APSInt &Value,
19204 QualType T) {
19205 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19206 "Integral type required!");
19207 unsigned BitWidth = Context.getIntWidth(T);
19208
19209 if (Value.isUnsigned() || Value.isNonNegative()) {
19210 if (T->isSignedIntegerOrEnumerationType())
19211 --BitWidth;
19212 return Value.getActiveBits() <= BitWidth;
19213 }
19214 return Value.getSignificantBits() <= BitWidth;
19215}
19216
19217// Given an integral type, return the next larger integral type
19218// (or a NULL type of no such type exists).
19220 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19221 // enum checking below.
19222 assert((T->isIntegralType(Context) ||
19223 T->isEnumeralType()) && "Integral type required!");
19224 const unsigned NumTypes = 4;
19225 QualType SignedIntegralTypes[NumTypes] = {
19226 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19227 };
19228 QualType UnsignedIntegralTypes[NumTypes] = {
19229 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19230 Context.UnsignedLongLongTy
19231 };
19232
19233 unsigned BitWidth = Context.getTypeSize(T);
19234 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19235 : UnsignedIntegralTypes;
19236 for (unsigned I = 0; I != NumTypes; ++I)
19237 if (Context.getTypeSize(Types[I]) > BitWidth)
19238 return Types[I];
19239
19240 return QualType();
19241}
19242
19244 EnumConstantDecl *LastEnumConst,
19245 SourceLocation IdLoc,
19247 Expr *Val) {
19248 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19249 llvm::APSInt EnumVal(IntWidth);
19250 QualType EltTy;
19251
19253 Val = nullptr;
19254
19255 if (Val)
19256 Val = DefaultLvalueConversion(Val).get();
19257
19258 if (Val) {
19259 if (Enum->isDependentType() || Val->isTypeDependent() ||
19260 Val->containsErrors())
19261 EltTy = Context.DependentTy;
19262 else {
19263 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19264 // underlying type, but do allow it in all other contexts.
19265 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19266 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19267 // constant-expression in the enumerator-definition shall be a converted
19268 // constant expression of the underlying type.
19269 EltTy = Enum->getIntegerType();
19270 ExprResult Converted =
19271 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19273 if (Converted.isInvalid())
19274 Val = nullptr;
19275 else
19276 Val = Converted.get();
19277 } else if (!Val->isValueDependent() &&
19278 !(Val =
19280 .get())) {
19281 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19282 } else {
19283 if (Enum->isComplete()) {
19284 EltTy = Enum->getIntegerType();
19285
19286 // In Obj-C and Microsoft mode, require the enumeration value to be
19287 // representable in the underlying type of the enumeration. In C++11,
19288 // we perform a non-narrowing conversion as part of converted constant
19289 // expression checking.
19290 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19292 .getTriple()
19293 .isWindowsMSVCEnvironment()) {
19294 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19295 } else {
19296 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19297 }
19298 }
19299
19300 // Cast to the underlying type.
19301 Val = ImpCastExprToType(Val, EltTy,
19302 EltTy->isBooleanType() ? CK_IntegralToBoolean
19303 : CK_IntegralCast)
19304 .get();
19305 } else if (getLangOpts().CPlusPlus) {
19306 // C++11 [dcl.enum]p5:
19307 // If the underlying type is not fixed, the type of each enumerator
19308 // is the type of its initializing value:
19309 // - If an initializer is specified for an enumerator, the
19310 // initializing value has the same type as the expression.
19311 EltTy = Val->getType();
19312 } else {
19313 // C99 6.7.2.2p2:
19314 // The expression that defines the value of an enumeration constant
19315 // shall be an integer constant expression that has a value
19316 // representable as an int.
19317
19318 // Complain if the value is not representable in an int.
19320 Diag(IdLoc, diag::ext_enum_value_not_int)
19321 << toString(EnumVal, 10) << Val->getSourceRange()
19322 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19323 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19324 // Force the type of the expression to 'int'.
19325 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19326 }
19327 EltTy = Val->getType();
19328 }
19329 }
19330 }
19331 }
19332
19333 if (!Val) {
19334 if (Enum->isDependentType())
19335 EltTy = Context.DependentTy;
19336 else if (!LastEnumConst) {
19337 // C++0x [dcl.enum]p5:
19338 // If the underlying type is not fixed, the type of each enumerator
19339 // is the type of its initializing value:
19340 // - If no initializer is specified for the first enumerator, the
19341 // initializing value has an unspecified integral type.
19342 //
19343 // GCC uses 'int' for its unspecified integral type, as does
19344 // C99 6.7.2.2p3.
19345 if (Enum->isFixed()) {
19346 EltTy = Enum->getIntegerType();
19347 }
19348 else {
19349 EltTy = Context.IntTy;
19350 }
19351 } else {
19352 // Assign the last value + 1.
19353 EnumVal = LastEnumConst->getInitVal();
19354 ++EnumVal;
19355 EltTy = LastEnumConst->getType();
19356
19357 // Check for overflow on increment.
19358 if (EnumVal < LastEnumConst->getInitVal()) {
19359 // C++0x [dcl.enum]p5:
19360 // If the underlying type is not fixed, the type of each enumerator
19361 // is the type of its initializing value:
19362 //
19363 // - Otherwise the type of the initializing value is the same as
19364 // the type of the initializing value of the preceding enumerator
19365 // unless the incremented value is not representable in that type,
19366 // in which case the type is an unspecified integral type
19367 // sufficient to contain the incremented value. If no such type
19368 // exists, the program is ill-formed.
19370 if (T.isNull() || Enum->isFixed()) {
19371 // There is no integral type larger enough to represent this
19372 // value. Complain, then allow the value to wrap around.
19373 EnumVal = LastEnumConst->getInitVal();
19374 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19375 ++EnumVal;
19376 if (Enum->isFixed())
19377 // When the underlying type is fixed, this is ill-formed.
19378 Diag(IdLoc, diag::err_enumerator_wrapped)
19379 << toString(EnumVal, 10)
19380 << EltTy;
19381 else
19382 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19383 << toString(EnumVal, 10);
19384 } else {
19385 EltTy = T;
19386 }
19387
19388 // Retrieve the last enumerator's value, extent that type to the
19389 // type that is supposed to be large enough to represent the incremented
19390 // value, then increment.
19391 EnumVal = LastEnumConst->getInitVal();
19392 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19393 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19394 ++EnumVal;
19395
19396 // If we're not in C++, diagnose the overflow of enumerator values,
19397 // which in C99 means that the enumerator value is not representable in
19398 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19399 // permits enumerator values that are representable in some larger
19400 // integral type.
19401 if (!getLangOpts().CPlusPlus && !T.isNull())
19402 Diag(IdLoc, diag::warn_enum_value_overflow);
19403 } else if (!getLangOpts().CPlusPlus &&
19404 !EltTy->isDependentType() &&
19405 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19406 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19407 Diag(IdLoc, diag::ext_enum_value_not_int)
19408 << toString(EnumVal, 10) << 1;
19409 }
19410 }
19411 }
19412
19413 if (!EltTy->isDependentType()) {
19414 // Make the enumerator value match the signedness and size of the
19415 // enumerator's type.
19416 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19417 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19418 }
19419
19420 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19421 Val, EnumVal);
19422}
19423
19425 SourceLocation IILoc) {
19426 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19428 return SkipBodyInfo();
19429
19430 // We have an anonymous enum definition. Look up the first enumerator to
19431 // determine if we should merge the definition with an existing one and
19432 // skip the body.
19433 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19435 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19436 if (!PrevECD)
19437 return SkipBodyInfo();
19438
19439 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19440 NamedDecl *Hidden;
19441 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19442 SkipBodyInfo Skip;
19443 Skip.Previous = Hidden;
19444 return Skip;
19445 }
19446
19447 return SkipBodyInfo();
19448}
19449
19450Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19452 const ParsedAttributesView &Attrs,
19453 SourceLocation EqualLoc, Expr *Val) {
19454 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19455 EnumConstantDecl *LastEnumConst =
19456 cast_or_null<EnumConstantDecl>(lastEnumConst);
19457
19458 // The scope passed in may not be a decl scope. Zip up the scope tree until
19459 // we find one that is.
19460 S = getNonFieldDeclScope(S);
19461
19462 // Verify that there isn't already something declared with this name in this
19463 // scope.
19465 LookupName(R, S);
19466 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19467
19468 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19469 // Maybe we will complain about the shadowed template parameter.
19470 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19471 // Just pretend that we didn't see the previous declaration.
19472 PrevDecl = nullptr;
19473 }
19474
19475 // C++ [class.mem]p15:
19476 // If T is the name of a class, then each of the following shall have a name
19477 // different from T:
19478 // - every enumerator of every member of class T that is an unscoped
19479 // enumerated type
19480 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19482 DeclarationNameInfo(Id, IdLoc));
19483
19484 EnumConstantDecl *New =
19485 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19486 if (!New)
19487 return nullptr;
19488
19489 if (PrevDecl) {
19490 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19491 // Check for other kinds of shadowing not already handled.
19492 CheckShadow(New, PrevDecl, R);
19493 }
19494
19495 // When in C++, we may get a TagDecl with the same name; in this case the
19496 // enum constant will 'hide' the tag.
19497 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19498 "Received TagDecl when not in C++!");
19499 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19500 if (isa<EnumConstantDecl>(PrevDecl))
19501 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19502 else
19503 Diag(IdLoc, diag::err_redefinition) << Id;
19504 notePreviousDefinition(PrevDecl, IdLoc);
19505 return nullptr;
19506 }
19507 }
19508
19509 // Process attributes.
19510 ProcessDeclAttributeList(S, New, Attrs);
19511 AddPragmaAttributes(S, New);
19512
19513 // Register this decl in the current scope stack.
19514 New->setAccess(TheEnumDecl->getAccess());
19515 PushOnScopeChains(New, S);
19516
19518
19519 return New;
19520}
19521
19522// Returns true when the enum initial expression does not trigger the
19523// duplicate enum warning. A few common cases are exempted as follows:
19524// Element2 = Element1
19525// Element2 = Element1 + 1
19526// Element2 = Element1 - 1
19527// Where Element2 and Element1 are from the same enum.
19529 Expr *InitExpr = ECD->getInitExpr();
19530 if (!InitExpr)
19531 return true;
19532 InitExpr = InitExpr->IgnoreImpCasts();
19533
19534 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19535 if (!BO->isAdditiveOp())
19536 return true;
19537 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19538 if (!IL)
19539 return true;
19540 if (IL->getValue() != 1)
19541 return true;
19542
19543 InitExpr = BO->getLHS();
19544 }
19545
19546 // This checks if the elements are from the same enum.
19547 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19548 if (!DRE)
19549 return true;
19550
19551 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19552 if (!EnumConstant)
19553 return true;
19554
19555 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19556 Enum)
19557 return true;
19558
19559 return false;
19560}
19561
19562// Emits a warning when an element is implicitly set a value that
19563// a previous element has already been set to.
19565 EnumDecl *Enum, QualType EnumType) {
19566 // Avoid anonymous enums
19567 if (!Enum->getIdentifier())
19568 return;
19569
19570 // Only check for small enums.
19571 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19572 return;
19573
19574 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19575 return;
19576
19577 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19578 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19579
19580 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19581
19582 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19583 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19584
19585 // Use int64_t as a key to avoid needing special handling for map keys.
19586 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19587 llvm::APSInt Val = D->getInitVal();
19588 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19589 };
19590
19591 DuplicatesVector DupVector;
19592 ValueToVectorMap EnumMap;
19593
19594 // Populate the EnumMap with all values represented by enum constants without
19595 // an initializer.
19596 for (auto *Element : Elements) {
19597 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19598
19599 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19600 // this constant. Skip this enum since it may be ill-formed.
19601 if (!ECD) {
19602 return;
19603 }
19604
19605 // Constants with initializers are handled in the next loop.
19606 if (ECD->getInitExpr())
19607 continue;
19608
19609 // Duplicate values are handled in the next loop.
19610 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19611 }
19612
19613 if (EnumMap.size() == 0)
19614 return;
19615
19616 // Create vectors for any values that has duplicates.
19617 for (auto *Element : Elements) {
19618 // The last loop returned if any constant was null.
19620 if (!ValidDuplicateEnum(ECD, Enum))
19621 continue;
19622
19623 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19624 if (Iter == EnumMap.end())
19625 continue;
19626
19627 DeclOrVector& Entry = Iter->second;
19628 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19629 // Ensure constants are different.
19630 if (D == ECD)
19631 continue;
19632
19633 // Create new vector and push values onto it.
19634 auto Vec = std::make_unique<ECDVector>();
19635 Vec->push_back(D);
19636 Vec->push_back(ECD);
19637
19638 // Update entry to point to the duplicates vector.
19639 Entry = Vec.get();
19640
19641 // Store the vector somewhere we can consult later for quick emission of
19642 // diagnostics.
19643 DupVector.emplace_back(std::move(Vec));
19644 continue;
19645 }
19646
19647 ECDVector *Vec = Entry.get<ECDVector*>();
19648 // Make sure constants are not added more than once.
19649 if (*Vec->begin() == ECD)
19650 continue;
19651
19652 Vec->push_back(ECD);
19653 }
19654
19655 // Emit diagnostics.
19656 for (const auto &Vec : DupVector) {
19657 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19658
19659 // Emit warning for one enum constant.
19660 auto *FirstECD = Vec->front();
19661 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19662 << FirstECD << toString(FirstECD->getInitVal(), 10)
19663 << FirstECD->getSourceRange();
19664
19665 // Emit one note for each of the remaining enum constants with
19666 // the same value.
19667 for (auto *ECD : llvm::drop_begin(*Vec))
19668 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19669 << ECD << toString(ECD->getInitVal(), 10)
19670 << ECD->getSourceRange();
19671 }
19672}
19673
19674bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19675 bool AllowMask) const {
19676 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19677 assert(ED->isCompleteDefinition() && "expected enum definition");
19678
19679 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19680 llvm::APInt &FlagBits = R.first->second;
19681
19682 if (R.second) {
19683 for (auto *E : ED->enumerators()) {
19684 const auto &EVal = E->getInitVal();
19685 // Only single-bit enumerators introduce new flag values.
19686 if (EVal.isPowerOf2())
19687 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19688 }
19689 }
19690
19691 // A value is in a flag enum if either its bits are a subset of the enum's
19692 // flag bits (the first condition) or we are allowing masks and the same is
19693 // true of its complement (the second condition). When masks are allowed, we
19694 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19695 //
19696 // While it's true that any value could be used as a mask, the assumption is
19697 // that a mask will have all of the insignificant bits set. Anything else is
19698 // likely a logic error.
19699 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19700 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19701}
19702
19704 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19705 const ParsedAttributesView &Attrs) {
19706 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19708
19709 ProcessDeclAttributeList(S, Enum, Attrs);
19710
19711 if (Enum->isDependentType()) {
19712 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19713 EnumConstantDecl *ECD =
19714 cast_or_null<EnumConstantDecl>(Elements[i]);
19715 if (!ECD) continue;
19716
19717 ECD->setType(EnumType);
19718 }
19719
19720 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19721 return;
19722 }
19723
19724 // TODO: If the result value doesn't fit in an int, it must be a long or long
19725 // long value. ISO C does not support this, but GCC does as an extension,
19726 // emit a warning.
19727 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19728 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19729 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19730
19731 // Verify that all the values are okay, compute the size of the values, and
19732 // reverse the list.
19733 unsigned NumNegativeBits = 0;
19734 unsigned NumPositiveBits = 0;
19735
19736 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19737 EnumConstantDecl *ECD =
19738 cast_or_null<EnumConstantDecl>(Elements[i]);
19739 if (!ECD) continue; // Already issued a diagnostic.
19740
19741 const llvm::APSInt &InitVal = ECD->getInitVal();
19742
19743 // Keep track of the size of positive and negative values.
19744 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19745 // If the enumerator is zero that should still be counted as a positive
19746 // bit since we need a bit to store the value zero.
19747 unsigned ActiveBits = InitVal.getActiveBits();
19748 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19749 } else {
19750 NumNegativeBits =
19751 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19752 }
19753 }
19754
19755 // If we have an empty set of enumerators we still need one bit.
19756 // From [dcl.enum]p8
19757 // If the enumerator-list is empty, the values of the enumeration are as if
19758 // the enumeration had a single enumerator with value 0
19759 if (!NumPositiveBits && !NumNegativeBits)
19760 NumPositiveBits = 1;
19761
19762 // Figure out the type that should be used for this enum.
19763 QualType BestType;
19764 unsigned BestWidth;
19765
19766 // C++0x N3000 [conv.prom]p3:
19767 // An rvalue of an unscoped enumeration type whose underlying
19768 // type is not fixed can be converted to an rvalue of the first
19769 // of the following types that can represent all the values of
19770 // the enumeration: int, unsigned int, long int, unsigned long
19771 // int, long long int, or unsigned long long int.
19772 // C99 6.4.4.3p2:
19773 // An identifier declared as an enumeration constant has type int.
19774 // The C99 rule is modified by a gcc extension
19775 QualType BestPromotionType;
19776
19777 bool Packed = Enum->hasAttr<PackedAttr>();
19778 // -fshort-enums is the equivalent to specifying the packed attribute on all
19779 // enum definitions.
19780 if (LangOpts.ShortEnums)
19781 Packed = true;
19782
19783 // If the enum already has a type because it is fixed or dictated by the
19784 // target, promote that type instead of analyzing the enumerators.
19785 if (Enum->isComplete()) {
19786 BestType = Enum->getIntegerType();
19787 if (Context.isPromotableIntegerType(BestType))
19788 BestPromotionType = Context.getPromotedIntegerType(BestType);
19789 else
19790 BestPromotionType = BestType;
19791
19792 BestWidth = Context.getIntWidth(BestType);
19793 }
19794 else if (NumNegativeBits) {
19795 // If there is a negative value, figure out the smallest integer type (of
19796 // int/long/longlong) that fits.
19797 // If it's packed, check also if it fits a char or a short.
19798 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19799 BestType = Context.SignedCharTy;
19800 BestWidth = CharWidth;
19801 } else if (Packed && NumNegativeBits <= ShortWidth &&
19802 NumPositiveBits < ShortWidth) {
19803 BestType = Context.ShortTy;
19804 BestWidth = ShortWidth;
19805 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19806 BestType = Context.IntTy;
19807 BestWidth = IntWidth;
19808 } else {
19809 BestWidth = Context.getTargetInfo().getLongWidth();
19810
19811 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19812 BestType = Context.LongTy;
19813 } else {
19814 BestWidth = Context.getTargetInfo().getLongLongWidth();
19815
19816 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19817 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19818 BestType = Context.LongLongTy;
19819 }
19820 }
19821 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19822 } else {
19823 // If there is no negative value, figure out the smallest type that fits
19824 // all of the enumerator values.
19825 // If it's packed, check also if it fits a char or a short.
19826 if (Packed && NumPositiveBits <= CharWidth) {
19827 BestType = Context.UnsignedCharTy;
19828 BestPromotionType = Context.IntTy;
19829 BestWidth = CharWidth;
19830 } else if (Packed && NumPositiveBits <= ShortWidth) {
19831 BestType = Context.UnsignedShortTy;
19832 BestPromotionType = Context.IntTy;
19833 BestWidth = ShortWidth;
19834 } else if (NumPositiveBits <= IntWidth) {
19835 BestType = Context.UnsignedIntTy;
19836 BestWidth = IntWidth;
19837 BestPromotionType
19838 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19840 } else if (NumPositiveBits <=
19841 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19842 BestType = Context.UnsignedLongTy;
19843 BestPromotionType
19844 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19846 } else {
19847 BestWidth = Context.getTargetInfo().getLongLongWidth();
19848 assert(NumPositiveBits <= BestWidth &&
19849 "How could an initializer get larger than ULL?");
19850 BestType = Context.UnsignedLongLongTy;
19851 BestPromotionType
19852 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19854 }
19855 }
19856
19857 // Loop over all of the enumerator constants, changing their types to match
19858 // the type of the enum if needed.
19859 for (auto *D : Elements) {
19860 auto *ECD = cast_or_null<EnumConstantDecl>(D);
19861 if (!ECD) continue; // Already issued a diagnostic.
19862
19863 // Standard C says the enumerators have int type, but we allow, as an
19864 // extension, the enumerators to be larger than int size. If each
19865 // enumerator value fits in an int, type it as an int, otherwise type it the
19866 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19867 // that X has type 'int', not 'unsigned'.
19868
19869 // Determine whether the value fits into an int.
19870 llvm::APSInt InitVal = ECD->getInitVal();
19871
19872 // If it fits into an integer type, force it. Otherwise force it to match
19873 // the enum decl type.
19874 QualType NewTy;
19875 unsigned NewWidth;
19876 bool NewSign;
19877 if (!getLangOpts().CPlusPlus &&
19878 !Enum->isFixed() &&
19880 NewTy = Context.IntTy;
19881 NewWidth = IntWidth;
19882 NewSign = true;
19883 } else if (ECD->getType() == BestType) {
19884 // Already the right type!
19885 if (getLangOpts().CPlusPlus)
19886 // C++ [dcl.enum]p4: Following the closing brace of an
19887 // enum-specifier, each enumerator has the type of its
19888 // enumeration.
19889 ECD->setType(EnumType);
19890 continue;
19891 } else {
19892 NewTy = BestType;
19893 NewWidth = BestWidth;
19894 NewSign = BestType->isSignedIntegerOrEnumerationType();
19895 }
19896
19897 // Adjust the APSInt value.
19898 InitVal = InitVal.extOrTrunc(NewWidth);
19899 InitVal.setIsSigned(NewSign);
19900 ECD->setInitVal(InitVal);
19901
19902 // Adjust the Expr initializer and type.
19903 if (ECD->getInitExpr() &&
19904 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
19905 ECD->setInitExpr(ImplicitCastExpr::Create(
19906 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
19907 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
19908 if (getLangOpts().CPlusPlus)
19909 // C++ [dcl.enum]p4: Following the closing brace of an
19910 // enum-specifier, each enumerator has the type of its
19911 // enumeration.
19912 ECD->setType(EnumType);
19913 else
19914 ECD->setType(NewTy);
19915 }
19916
19917 Enum->completeDefinition(BestType, BestPromotionType,
19918 NumPositiveBits, NumNegativeBits);
19919
19920 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
19921
19922 if (Enum->isClosedFlag()) {
19923 for (Decl *D : Elements) {
19924 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
19925 if (!ECD) continue; // Already issued a diagnostic.
19926
19927 llvm::APSInt InitVal = ECD->getInitVal();
19928 if (InitVal != 0 && !InitVal.isPowerOf2() &&
19929 !IsValueInFlagEnum(Enum, InitVal, true))
19930 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
19931 << ECD << Enum;
19932 }
19933 }
19934
19935 // Now that the enum type is defined, ensure it's not been underaligned.
19936 if (Enum->hasAttrs())
19938}
19939
19941 SourceLocation StartLoc,
19942 SourceLocation EndLoc) {
19944
19946 AsmString, StartLoc,
19947 EndLoc);
19948 CurContext->addDecl(New);
19949 return New;
19950}
19951
19953 auto *New = TopLevelStmtDecl::Create(Context, Statement);
19955 return New;
19956}
19957
19959 IdentifierInfo* AliasName,
19960 SourceLocation PragmaLoc,
19961 SourceLocation NameLoc,
19962 SourceLocation AliasNameLoc) {
19963 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
19965 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
19967 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
19968 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
19969
19970 // If a declaration that:
19971 // 1) declares a function or a variable
19972 // 2) has external linkage
19973 // already exists, add a label attribute to it.
19974 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
19975 if (isDeclExternC(PrevDecl))
19976 PrevDecl->addAttr(Attr);
19977 else
19978 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
19979 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
19980 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
19981 } else
19982 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
19983}
19984
19986 SourceLocation PragmaLoc,
19987 SourceLocation NameLoc) {
19988 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
19989
19990 if (PrevDecl) {
19991 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
19992 } else {
19993 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
19994 }
19995}
19996
19998 IdentifierInfo* AliasName,
19999 SourceLocation PragmaLoc,
20000 SourceLocation NameLoc,
20001 SourceLocation AliasNameLoc) {
20002 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20004 WeakInfo W = WeakInfo(Name, NameLoc);
20005
20006 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20007 if (!PrevDecl->hasAttr<AliasAttr>())
20008 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20010 } else {
20011 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20012 }
20013}
20014
20016 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20017}
20018
20020 bool Final) {
20021 assert(FD && "Expected non-null FunctionDecl");
20022
20023 // SYCL functions can be template, so we check if they have appropriate
20024 // attribute prior to checking if it is a template.
20025 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20027
20028 // Templates are emitted when they're instantiated.
20029 if (FD->isDependentContext())
20031
20032 // Check whether this function is an externally visible definition.
20033 auto IsEmittedForExternalSymbol = [this, FD]() {
20034 // We have to check the GVA linkage of the function's *definition* -- if we
20035 // only have a declaration, we don't know whether or not the function will
20036 // be emitted, because (say) the definition could include "inline".
20037 const FunctionDecl *Def = FD->getDefinition();
20038
20039 return Def && !isDiscardableGVALinkage(
20040 getASTContext().GetGVALinkageForFunction(Def));
20041 };
20042
20043 if (LangOpts.OpenMPIsTargetDevice) {
20044 // In OpenMP device mode we will not emit host only functions, or functions
20045 // we don't need due to their linkage.
20046 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20047 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20048 // DevTy may be changed later by
20049 // #pragma omp declare target to(*) device_type(*).
20050 // Therefore DevTy having no value does not imply host. The emission status
20051 // will be checked again at the end of compilation unit with Final = true.
20052 if (DevTy)
20053 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20055 // If we have an explicit value for the device type, or we are in a target
20056 // declare context, we need to emit all extern and used symbols.
20057 if (isInOpenMPDeclareTargetContext() || DevTy)
20058 if (IsEmittedForExternalSymbol())
20060 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20061 // we'll omit it.
20062 if (Final)
20064 } else if (LangOpts.OpenMP > 45) {
20065 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20066 // function. In 5.0, no_host was introduced which might cause a function to
20067 // be ommitted.
20068 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20069 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20070 if (DevTy)
20071 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20073 }
20074
20075 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20077
20078 if (LangOpts.CUDA) {
20079 // When compiling for device, host functions are never emitted. Similarly,
20080 // when compiling for host, device and global functions are never emitted.
20081 // (Technically, we do emit a host-side stub for global functions, but this
20082 // doesn't count for our purposes here.)
20084 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20086 if (!LangOpts.CUDAIsDevice &&
20087 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20089
20090 if (IsEmittedForExternalSymbol())
20092 }
20093
20094 // Otherwise, the function is known-emitted if it's in our set of
20095 // known-emitted functions.
20097}
20098
20100 // Host-side references to a __global__ function refer to the stub, so the
20101 // function itself is never emitted and therefore should not be marked.
20102 // If we have host fn calls kernel fn calls host+device, the HD function
20103 // does not get instantiated on the host. We model this by omitting at the
20104 // call to the kernel from the callgraph. This ensures that, when compiling
20105 // for host, only HD functions actually called from the host get marked as
20106 // known-emitted.
20107 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20108 IdentifyCUDATarget(Callee) == CFT_Global;
20109}
Defines the clang::ASTContext interface.
NodeId Parent
Definition ASTDiff.cpp:191
int Id
Definition ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
MatchType Type
StringRef P
#define SM(sm)
Definition Cuda.cpp:80
auto * N
static constexpr Builtin::Info BuiltinInfo[]
Definition Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
llvm::Error Error
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2173
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
const Environment & Env
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:58
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static bool hasAttr(const FunctionDecl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:108
static bool isFunctionOrMethod(const Decl *D)
isFunctionOrMethod - Return true if the given decl has function type (function or function-typed vari...
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:187
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:242
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:836
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, Sema::CXXSpecialMember CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:589
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, Sema::CXXSpecialMember CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:609
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static bool MultiVersionTypesCompatible(MultiVersionKind Old, MultiVersionKind New)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:851
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition SemaDecl.cpp:283
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D)
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
const NestedNameSpecifier * Specifier
std::string Label
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
Definition Expr.h:1501
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition ASTConsumer.h:72
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition ASTConsumer.h:57
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:182
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition ASTContext.h:691
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getParenType(QualType NamedType) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition ASTContext.h:634
QualType getObjCClassType() const
Represents the Objective-C Class type.
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
IdentifierTable & Idents
Definition ASTContext.h:630
Builtin::Context & BuiltinInfo
Definition ASTContext.h:632
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition ASTContext.h:761
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
CanQualType UnsignedLongTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType CharTy
CanQualType IntTy
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:683
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
CanQualType ShortTy
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:743
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc.
Definition Ownership.h:152
bool isInvalid() const
Definition Ownership.h:165
bool isUsable() const
Definition Ownership.h:166
PtrTy get() const
Definition Ownership.h:169
bool isUnset() const
Definition Ownership.h:167
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition Type.h:2849
Wrapper for source info for arrays.
Definition TypeLoc.h:1524
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1526
Expr * getSizeExpr() const
Definition TypeLoc.h:1546
TypeLoc getElementLoc() const
Definition TypeLoc.h:1554
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1534
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition Type.h:3063
QualType getElementType() const
Definition Type.h:3084
Attr - This represents one attribute.
Definition Attr.h:40
attr::Kind getKind() const
Definition Attr.h:80
bool isInherited() const
Definition Attr.h:89
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:94
SourceLocation getLocation() const
Definition Attr.h:87
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:618
AttributeFactory & getFactory() const
Definition ParsedAttr.h:713
Type source information for an attributed type.
Definition TypeLoc.h:868
const T * getAttrAs()
Definition TypeLoc.h:894
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:882
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4234
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition Expr.h:4288
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4276
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3833
Expr * getLHS() const
Definition Expr.h:3882
Expr * getRHS() const
Definition Expr.h:3884
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:3973
A binding in a decomposition declaration.
Definition DeclCXX.h:4060
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4371
bool doesNotEscape() const
Definition Decl.h:4522
This class is used for builtin types like 'int'.
Definition Type.h:2662
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition Builtins.cpp:209
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition Builtins.h:262
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:222
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition Builtins.h:137
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition Builtins.h:247
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition Builtins.h:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition Builtins.h:167
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition Builtins.cpp:204
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition Builtins.h:160
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition Builtins.cpp:199
bool isConstWithoutExceptions(unsigned ID) const
Definition Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition Builtins.h:122
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:190
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:191
Represents a call to a C++ constructor.
Definition ExprCXX.h:1518
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1596
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1669
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1590
Represents a C++ constructor within a class.
Definition DeclCXX.h:2491
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:2695
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2656
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2818
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2823
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition DeclCXX.cpp:2115
Represents a C++ destructor within a class.
Definition DeclCXX.h:2755
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2790
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2035
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2454
bool isVirtual() const
Definition DeclCXX.h:2079
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2150
QualType getThisType() const
Return the type of the this pointer.
Definition DeclCXX.cpp:2504
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2433
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition DeclCXX.cpp:2232
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2180
bool isConst() const
Definition DeclCXX.h:2076
bool isStatic() const
Definition DeclCXX.cpp:2144
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2412
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2120
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:81
Represents a C++ struct/union/class.
Definition DeclCXX.h:254
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition DeclCXX.h:1316
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1222
base_class_iterator bases_end()
Definition DeclCXX.h:615
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1348
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1537
base_class_range bases()
Definition DeclCXX.h:606
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1358
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:552
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:600
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition DeclCXX.cpp:131
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:613
capture_const_range captures() const
Definition DeclCXX.h:1082
bool hasDefinition() const
Definition DeclCXX.h:559
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:1855
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:1859
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition DeclCXX.h:1270
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:511
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:126
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2831
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3022
bool isCallToStdMove() const
Definition Expr.cpp:3499
Expr * getCallee()
Definition Expr.h:2981
arg_range arguments()
Definition Expr.h:3070
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastKind getCastKind() const
Definition Expr.h:3545
Expr * getSubExpr()
Definition Expr.h:3551
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a function specialization at template class scope.
static ClassScopeFunctionSpecializationDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD, bool HasExplicitTemplateArgs, const TemplateArgumentListInfo &TemplateArgs)
Declaration of a class template.
ConditionalOperator - The ?: ternary operator.
Definition Expr.h:4172
const llvm::APInt & getSize() const
Definition Type.h:3132
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:143
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:178
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:28
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition DeclBase.h:1347
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition DeclBase.h:2226
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1409
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:1951
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2075
bool isFileContext() const
Definition DeclBase.h:2021
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isObjCContainer() const
Definition DeclBase.h:1990
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:1967
bool isNamespace() const
Definition DeclBase.h:2035
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2026
bool isRecord() const
Definition DeclBase.h:2030
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2206
bool isFunctionOrMethod() const
Definition DeclBase.h:2003
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:1944
DeclContext * getNonTransparentContext()
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:68
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1242
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:601
ValueDecl * getDecl()
Definition Expr.h:1310
Captures information about "declaration specifiers".
Definition DeclSpec.h:246
bool isVirtualSpecified() const
Definition DeclSpec.h:614
bool isModulePrivateSpecified() const
Definition DeclSpec.h:790
static const TST TST_typeof_unqualType
Definition DeclSpec.h:308
bool hasAutoTypeSpec() const
Definition DeclSpec.h:562
static const TST TST_typename
Definition DeclSpec.h:305
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:626
void ClearStorageClassSpecs()
Definition DeclSpec.h:489
bool isNoreturnSpecified() const
Definition DeclSpec.h:627
TST getTypeSpecType() const
Definition DeclSpec.h:511
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:484
SCS getStorageClassSpec() const
Definition DeclSpec.h:475
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:832
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:542
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:541
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:675
static const TST TST_interface
Definition DeclSpec.h:303
static const TST TST_typeofExpr
Definition DeclSpec.h:307
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:583
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:674
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:628
bool isExternInLinkageSpec() const
Definition DeclSpec.h:479
static const TST TST_union
Definition DeclSpec.h:301
SCS
storage-class-specifier
Definition DeclSpec.h:250
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:620
static const TST TST_int
Definition DeclSpec.h:284
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:791
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:521
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:751
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:476
ParsedAttributes & getAttributes()
Definition DeclSpec.h:834
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:592
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:584
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:621
Expr * getRepAsExpr() const
Definition DeclSpec.h:529
static const TST TST_enum
Definition DeclSpec.h:300
static const TST TST_decltype
Definition DeclSpec.h:310
static bool isDeclRep(TST T)
Definition DeclSpec.h:443
bool isInlineSpecified() const
Definition DeclSpec.h:603
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:585
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:309
static const TST TST_class
Definition DeclSpec.h:304
void ClearConstexprSpec()
Definition DeclSpec.h:802
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:545
static const TST TST_atomic
Definition DeclSpec.h:318
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:485
Decl * getRepAsDecl() const
Definition DeclSpec.h:525
static const TST TST_unspecified
Definition DeclSpec.h:277
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:587
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:615
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:797
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:538
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:549
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:755
static const TSCS TSCS_thread_local
Definition DeclSpec.h:266
static const TST TST_error
Definition DeclSpec.h:322
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:610
bool isTypeSpecOwned() const
Definition DeclSpec.h:515
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:588
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:586
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:784
bool hasExplicitSpecifier() const
Definition DeclSpec.h:617
bool hasConstexprSpecifier() const
Definition DeclSpec.h:798
static const TST TST_typeofType
Definition DeclSpec.h:306
static const TST TST_auto
Definition DeclSpec.h:315
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:793
static const TST TST_struct
Definition DeclSpec.h:302
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:83
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1029
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1044
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:296
bool isInStdNamespace() const
Definition DeclBase.cpp:404
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:428
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1194
T * getAttr() const
Definition DeclBase.h:556
bool hasAttrs() const
Definition DeclBase.h:502
void addAttr(Attr *A)
Definition DeclBase.cpp:904
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:576
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:504
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:732
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1119
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:100
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1585
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:133
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:615
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:861
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1187
@ FOK_None
Not a friend object.
Definition DeclBase.h:1185
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1186
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:263
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:483
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:811
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:228
void dropAttrs()
Definition DeclBase.cpp:897
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:207
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1148
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2623
bool isInvalidDecl() const
Definition DeclBase.h:571
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1137
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:542
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:486
SourceLocation getLocation() const
Definition DeclBase.h:432
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:141
void setLocalOwningModule(Module *M)
Definition DeclBase.h:798
void setImplicit(bool I=true)
Definition DeclBase.h:577
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition DeclBase.h:591
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:458
DeclContext * getDeclContext()
Definition DeclBase.h:441
attr_range attrs() const
Definition DeclBase.h:519
AccessSpecifier getAccess() const
Definition DeclBase.h:491
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:424
bool hasOwningModule() const
Is this declaration owned by some module?
Definition DeclBase.h:806
void dropAttr()
Definition DeclBase.h:531
AttrVec & getAttrs()
Definition DeclBase.h:508
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:337
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:886
bool hasAttr() const
Definition DeclBase.h:560
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1203
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:341
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:946
Kind getKind() const
Definition DeclBase.h:435
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:765
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:823
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:808
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:1993
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2033
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1931
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:817
unsigned getNumTemplateParameterLists() const
Definition Decl.h:853
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:800
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:1943
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:841
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:794
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:1977
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1850
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2378
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2277
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2320
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:1986
Expr * getAsmLabel() const
Definition DeclSpec.h:2624
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2659
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2605
void setRedeclaration(bool Val)
Definition DeclSpec.h:2680
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2274
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2023
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2555
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2635
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2585
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2316
bool isRedeclaration() const
Definition DeclSpec.h:2681
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2608
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2007
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2022
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:423
bool isFunctionDefinition() const
Definition DeclSpec.h:2655
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2005
bool hasInitializer() const
Definition DeclSpec.h:2664
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2651
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2001
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition DeclSpec.h:2598
IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2268
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2291
bool isInvalidType() const
Definition DeclSpec.h:2636
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2021
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2264
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2667
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:415
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:1993
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2409
A decomposition declaration.
Definition DeclCXX.h:4119
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3289
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1741
SourceRange getSourceRange() const
Definition DeclSpec.h:1786
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1784
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2375
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2355
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2364
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:911
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition Diagnostic.h:926
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2275
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2289
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3189
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5261
const Expr * getInitExpr() const
Definition Decl.h:3208
const llvm::APSInt & getInitVal() const
Definition Decl.h:3210
Represents an enum.
Definition Decl.h:3750
enumerator_range enumerators() const
Definition Decl.h:3883
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:3955
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:3919
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:3922
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:3969
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:4681
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:4726
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:3964
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:4701
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:3905
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:3910
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1882
This represents one expression.
Definition Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:169
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:186
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3072
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition Expr.h:239
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3068
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3052
bool isConstantInitializer(ASTContext &Ctx, bool ForRef, const Expr **Culprit=nullptr) const
isConstantInitializer - Returns true if this expression can be emitted to IR as a constant,...
Definition Expr.cpp:3300
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:330
QualType getType() const
Definition Expr.h:142
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:2960
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3048
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4404
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition Decl.cpp:4441
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3166
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4389
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5391
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:97
Represents a function declaration or definition.
Definition Decl.h:1917
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2532
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2624
bool isPure() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2255
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2371
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3491
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:3921
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:3916
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2216
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2544
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2523
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3747
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3520
param_iterator param_end()
Definition Decl.h:2614
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2731
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2538
QualType getReturnType() const
Definition Decl.h:2655
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2601
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3477
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2284
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2272
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3389
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4030
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2343
void setWillHaveBody(bool V=true)
Definition Decl.h:2529
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2338
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4040
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3505
param_iterator param_begin()
Definition Decl.h:2613
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3026
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2228
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2435
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3216
void setPure(bool P=true)
Definition Decl.cpp:3157
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:3974
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2698
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4222
void setTrivial(bool IT)
Definition Decl.h:2273
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:3867
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2365
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition Decl.h:2360
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3393
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2259
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2323
bool isImmediateEscalating() const
Definition Decl.cpp:3170
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2251
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2522
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2184
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3208
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2726
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.cpp:3268
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition Decl.h:2093
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3082
void setRangeEnd(SourceLocation E)
Definition Decl.h:2122
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3473
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2280
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2316
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4245
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2743
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:3861
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:3853
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2368
void setDefaulted(bool D=true)
Definition Decl.h:2281
bool isConsteval() const
Definition Decl.h:2377
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2672
void setBody(Stmt *B)
Definition Decl.cpp:3150
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3407
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.h:2814
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2354
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:3888
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3580
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2115
void setDeletedAsWritten(bool D=true)
Definition Decl.h:2443
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3058
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2330
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3105
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:2709
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3459
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2528
Represents a prototype with parameter type info, e.g.
Definition Type.h:4076
unsigned getNumParams() const
Definition Type.h:4281
QualType getParamType(unsigned i) const
Definition Type.h:4283
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition Type.h:4312
bool isVariadic() const
Whether this function prototype is variadic.
Definition Type.h:4403
ExtProtoInfo getExtProtoInfo() const
Definition Type.h:4292
ArrayRef< QualType > getParamTypes() const
Definition Type.h:4288
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Wrapper for source info for functions.
Definition TypeLoc.h:1391
A class which abstracts out some details necessary for making a call.
Definition Type.h:3840
ExtInfo withCallingConv(CallingConv cc) const
Definition Type.h:3955
CallingConv getCC() const
Definition Type.h:3902
ExtInfo withProducesResult(bool producesResult) const
Definition Type.h:3921
unsigned getRegParm() const
Definition Type.h:3895
bool getNoCallerSavedRegs() const
Definition Type.h:3891
ExtInfo withNoReturn(bool noReturn) const
Definition Type.h:3914
bool getHasRegParm() const
Definition Type.h:3893
bool getNoReturn() const
Definition Type.h:3888
bool getProducesResult() const
Definition Type.h:3889
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition Type.h:3935
ExtInfo withRegParm(unsigned RegParm) const
Definition Type.h:3949
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition Type.h:3729
ExtInfo getExtInfo() const
Definition Type.h:4006
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3333
unsigned getRegParmType() const
Definition Type.h:3997
CallingConv getCallConv() const
Definition Type.h:4005
QualType getReturnType() const
Definition Type.h:3994
bool getCmseNSCallAttr() const
Definition Type.h:4004
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3648
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2090
Represents a C array with an unspecified size.
Definition Type.h:3169
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3229
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5289
void setInherited(bool I)
Definition Attr.h:146
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2462
Describes an C or C++ initializer list.
Definition Expr.h:4829
child_range children()
Definition Expr.h:5021
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:1000
Represents the declaration of a label.
Definition Decl.h:494
bool isResolvedMSAsmLabel() const
Definition Decl.h:529
LabelStmt * getStmt() const
Definition Decl.h:518
bool isMSAsmLabel() const
Definition Decl.h:528
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition LangOptions.h:82
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
clang::ObjCRuntime ObjCRuntime
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
void push_back(const T &LocalValue)
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1294
Represents a linkage specification.
Definition DeclCXX.h:2884
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:2853
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:643
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:689
Represents the results of name lookup.
Definition Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:59
DeclClass * getAsSingle() const
Definition Lookup.h:533
bool empty() const
Return true if no decls were found.
Definition Lookup.h:339
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:632
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:717
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:543
bool isAmbiguous() const
Definition Lookup.h:301
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:308
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:253
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition Lookup.h:638
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:550
LookupResultKind getResultKind() const
Definition Lookup.h:321
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:609
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:243
iterator end() const
Definition Lookup.h:336
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:135
iterator begin() const
Definition Lookup.h:335
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:233
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3194
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3273
Expr * getBase() const
Definition Expr.h:3267
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition Type.h:3011
Describes a module or submodule.
Definition Module.h:98
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:104
Module * Parent
The parent of this module.
Definition Module.h:147
bool isPrivateModule() const
Definition Module.h:201
bool isModulePurview() const
Does this Module scope describe part of the purview of a standard named C++ module?
Definition Module.h:176
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:562
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:573
StringRef getPrimaryModuleInterfaceName() const
Get the primary module interface name from a partition.
Definition Module.h:589
bool isModulePartition() const
Is this a module partition.
Definition Module.h:567
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:191
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:241
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:624
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:247
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:457
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:268
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1089
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:274
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:416
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:451
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:401
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:313
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1160
bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1811
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:664
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1887
bool isExternallyVisible() const
Definition Decl.h:405
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1100
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:369
Represent a C++ namespace.
Definition Decl.h:542
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:600
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2312
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2759
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:941
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:80
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2584
Represents an ObjC class declaration.
Definition DeclObjC.h:1147
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition DeclObjC.h:1530
known_extensions_range known_extensions() const
Definition DeclObjC.h:1749
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1939
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:942
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:138
param_const_iterator param_end() const
Definition DeclObjC.h:360
param_const_iterator param_begin() const
Definition DeclObjC.h:356
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:351
bool isOptional() const
Definition DeclObjC.h:506
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:352
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition ObjCRuntime.h:82
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition ObjCRuntime.h:97
Wrapper for void* pointer.
Definition Ownership.h:50
PtrTy get() const
Definition Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1150
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:954
@ CSK_Normal
Normal lookup.
Definition Overload.h:958
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1127
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:242
Expr ** getExprs()
Definition Expr.h:5645
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:5634
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1166
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1179
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1162
Sugar for parentheses used when specifying types.
Definition Type.h:2794
Represents a parameter to a function.
Definition Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1782
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1786
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1755
QualType getOriginalType() const
Definition Decl.cpp:2861
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2852
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:123
static const ParsedAttributesView & none()
Definition ParsedAttr.h:814
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:894
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:920
AttributePool & getPool() const
Definition ParsedAttr.h:926
PipeType - OpenCL20.
Definition Type.h:6532
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1245
Wrapper for source info for pointers.
Definition TypeLoc.h:1264
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1270
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition Type.h:2820
QualType getPointeeType() const
Definition Type.h:2830
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition Type.h:736
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition Type.h:6767
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:6830
@ DK_nontrivial_c_struct
Definition Type.h:1292
PrimitiveDefaultInitializeKind
Definition Type.h:1220
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2702
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition Type.h:982
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition Type.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition Type.h:803
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2750
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition Type.h:6684
LangAS getAddressSpace() const
Return the address space of this type.
Definition Type.h:6809
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:6824
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition Type.h:6724
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition Type.h:1205
QualType getCanonicalType() const
Definition Type.h:6736
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition Type.h:6777
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:2734
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition Type.h:1200
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition Type.h:6756
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition Type.h:1299
bool isCanonical() const
Definition Type.h:6741
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition Type.h:1077
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition Type.h:1100
bool hasNonTrivialObjCLifetime() const
Definition Type.h:1209
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2475
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition Type.h:1250
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition Type.h:1255
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:6818
A qualifier set is used to build a set of qualifiers.
Definition Type.h:6624
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition Type.h:6631
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4007
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition Type.h:174
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition Type.h:167
@ OCL_None
There is no lifetime qualification on this type.
Definition Type.h:163
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition Type.h:177
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition Type.h:180
bool hasConst() const
Definition Type.h:263
void removeConst()
Definition Type.h:265
void addConst()
Definition Type.h:266
ObjCLifetime getObjCLifetime() const
Definition Type.h:351
bool empty() const
Definition Type.h:439
Represents a struct/union/class.
Definition Decl.h:4028
bool hasObjectMember() const
Definition Decl.h:4110
field_range fields() const
Definition Decl.h:4255
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:4844
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition Decl.cpp:4863
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:4909
@ APK_CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4054
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4240
field_iterator field_begin() const
Definition Decl.cpp:4897
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:6605
void setMemberSpecialization()
Note that this member template is a specialization.
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
redecl_iterator redecls_end() const
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:4871
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Base for LValueReferenceType and RValueReferenceType.
Definition Type.h:2931
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:2840
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:2888
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:362
void RemoveDecl(Decl *D)
Definition Scope.h:334
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:365
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:528
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:254
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:78
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:60
bool IsAlignAttr() const
Definition Sema.h:544
Mode getAlignMode() const
Definition Sema.h:546
A RAII object to temporarily push a declaration context.
Definition Sema.h:1019
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:967
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:979
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:2747
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:2757
static NameClassification Unknown()
Definition Sema.h:2727
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:2731
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:2775
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:2763
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:2737
static NameClassification Concept(TemplateName Name)
Definition Sema.h:2769
static NameClassification UndeclaredNonType()
Definition Sema.h:2743
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:2751
static NameClassification Error()
Definition Sema.h:2723
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:9853
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:9884
A generic diagnostic builder for errors which may or may not be deferred.
Definition Sema.h:1795
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:356
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority)
Attribute merging methods. Return true if a new attribute was added.
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:3471
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:9911
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:13903
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:116
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old)
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:4335
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:4339
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:4358
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:4374
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:4371
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:4347
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:4342
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Decl * ActOnTopLevelStmtDecl(Stmt *Statement)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
NonTrivialCUnionContext
Definition Sema.h:3032
@ NTCUC_CopyInit
Definition Sema.h:3042
@ NTCUC_AutoVar
Definition Sema.h:3040
@ NTCUC_DefaultInitializedObject
Definition Sema.h:3038
@ NTCUC_FunctionReturn
Definition Sema.h:3036
@ NTCUC_FunctionParam
Definition Sema.h:3034
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition Sema.cpp:1897
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1491
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4549
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:871
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:470
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:862
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition Sema.h:1190
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:891
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
void ActOnExitFunctionContext()
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2246
Preprocessor & getPreprocessor() const
Definition Sema.h:1686
void deduceOpenCLAddressSpace(ValueDecl *decl)
void CheckHLSLEntryPoint(FunctionDecl *FD)
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:696
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckForFunctionMarkedFinal - Checks whether a virtual member function overrides a virtual member fun...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:53
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1475
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:672
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition Sema.h:1482
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:407
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:1684
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:60
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:699
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:912
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:1687
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:695
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:705
SmallVector< VarDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:904
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:3296
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1480
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:8502
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:1168
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:681
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:1143
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2127
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:167
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition Sema.h:1682
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:58
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2145
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:8707
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:8710
@ UPPC_Initializer
An initializer.
Definition Sema.h:8722
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:8695
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:8719
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:8698
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:8701
void checkAllowedCUDAInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:607
const LangOptions & getLangOpts() const
Definition Sema.h:1680
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition Sema.h:750
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:2383
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
bool TemplateParameterListsAreEqual(const NamedDecl *NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
Preprocessor & PP
Definition Sema.h:406
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:1920
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:629
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition Sema.h:405
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:9051
@ TDK_Success
Template argument deduction was successful.
Definition Sema.h:9053
@ TDK_AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:9105
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2361
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:2412
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:471
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:200
void CheckCXXDefaultArguments(FunctionDecl *FD)
CheckCXXDefaultArguments - Verify that the default arguments for a function declaration are well-form...
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
void MaybeAddCUDAConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:711
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:684
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:694
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:13913
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:900
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
void ExitDeclaratorContext(Scope *S)
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition Sema.h:11417
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition SemaAttr.cpp:851
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:2018
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
HLSLNumThreadsAttr * mergeHLSLNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:1648
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:640
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:2406
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition Sema.h:749
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:2373
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init)
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:419
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition Sema.h:4389
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
Definition Sema.h:4392
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition Sema.h:4395
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
Definition Sema.h:4399
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:659
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
ObjCContainerDecl * getObjCDeclContext() const
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
bool isInOpenMPDeclareVariantScope() const
Can we exit an OpenMP declare variant scope at the moment.
Definition Sema.h:11171
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:423
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:9762
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:3327
@ NTK_Typedef
Definition Sema.h:3332
@ NTK_NonUnion
Definition Sema.h:3330
@ NTK_TypeAlias
Definition Sema.h:3333
@ NTK_NonClass
Definition Sema.h:3329
@ NTK_NonEnum
Definition Sema.h:3331
@ NTK_NonStruct
Definition Sema.h:3328
@ NTK_TemplateTemplateArgument
Definition Sema.h:3336
@ NTK_TypeAliasTemplate
Definition Sema.h:3335
@ NTK_Template
Definition Sema.h:3334
void ActOnObjCContainerFinishDefinition()
SourceManager & getSourceManager() const
Definition Sema.h:1685
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init, ParenListExpr *PL=nullptr)
RedeclarationKind forRedeclarationInCurContext() const
Definition Sema.h:4402
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition Sema.h:472
@ NTCUK_Destruct
Definition Sema.h:3062
@ NTCUK_Init
Definition Sema.h:3061
@ NTCUK_Copy
Definition Sema.h:3063
PragmaClangSection PragmaClangDataSection
Definition Sema.h:469
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
void * SkippedDefinitionContext
Definition Sema.h:3513
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:89
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:815
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:223
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx)
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_NonError
Definition Sema.h:4576
@ CTK_ErrorRecovery
Definition Sema.h:4577
void CheckCompleteVariableDeclaration(VarDecl *VD)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2302
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:1164
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:619
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:3894
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
CUDAFunctionTarget
Definition Sema.h:13188
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:329
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
ASTConsumer & Consumer
Definition Sema.h:408
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:3771
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:3763
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:3767
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:807
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:9929
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1603
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
@ FirstDecl
Parsing the first decl in a TU.
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
bool inferObjCARCLifetime(ValueDecl *decl)
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:3633
@ AMK_None
Don't merge availability attributes at all.
Definition Sema.h:3635
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:3641
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:3644
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:3647
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:3638
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:74
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1161
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC #pragma optimize in scope,...
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:901
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:1422
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:410
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
DiagnosticsEngine & Diags
Definition Sema.h:409
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:1681
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:693
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
@ TUK_Definition
Definition Sema.h:3351
@ TUK_Declaration
Definition Sema.h:3350
@ TUK_Friend
Definition Sema.h:3352
@ TUK_Reference
Definition Sema.h:3349
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
@ TPC_FriendFunctionTemplate
Definition Sema.h:8230
@ TPC_ClassTemplateMember
Definition Sema.h:8228
@ TPC_FunctionTemplate
Definition Sema.h:8227
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:8231
@ TPC_VarTemplate
Definition Sema.h:8226
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
void DiagnoseUnusedDecl(const NamedDecl *ND)
void PopDeclContext()
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:1516
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition Sema.cpp:2344
@ OOK_Outside
Definition Sema.h:3357
@ OOK_Macro
Definition Sema.h:3362
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
HLSLShaderAttr * mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args)
Definition Sema.h:2546
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:1137
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:1880
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:468
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:8027
@ AbstractReturnType
Definition Sema.h:8025
@ AbstractFieldType
Definition Sema.h:8028
@ AbstractIvarType
Definition Sema.h:8029
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:1172
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc)
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:5340
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
CXXSpecialMember
Kinds of C++ special members.
Definition Sema.h:1567
@ CXXCopyConstructor
Definition Sema.h:1569
@ CXXMoveConstructor
Definition Sema.h:1570
@ CXXDestructor
Definition Sema.h:1573
@ CXXDefaultConstructor
Definition Sema.h:1568
@ CXXInvalid
Definition Sema.h:1574
@ CXXMoveAssignment
Definition Sema.h:1572
@ CXXCopyAssignment
Definition Sema.h:1571
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
std::string getCudaConfigureFuncName() const
Returns the name of the launch configuration function.
Definition SemaCUDA.cpp:950
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:1607
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
IdentifierResolver IdResolver
Definition Sema.h:1156
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition SemaDecl.cpp:129
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE=nullptr)
Builds an expression which might be an implicit member expression.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:721
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:1564
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition Sema.h:2868
void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition SemaCUDA.cpp:903
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:6953
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:72
child_range children()
Definition Stmt.cpp:286
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:325
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:337
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1793
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1938
StringRef getString() const
Definition Expr.h:1873
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3469
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:3742
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3592
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4589
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3567
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3553
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3572
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4566
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4557
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4549
bool isUnion() const
Definition Decl.h:3673
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:4612
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:4649
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3691
TagKind getTagKind() const
Definition Decl.h:3664
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Exposes information about the current target.
Definition TargetInfo.h:207
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:290
virtual bool validateCpuIs(StringRef Name) const
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition TargetInfo.h:479
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition TargetInfo.h:487
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition TargetInfo.h:497
bool isTLSSupported() const
Whether the target supports thread-local storage.
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
unsigned getCharWidth() const
Definition TargetInfo.h:474
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition TargetInfo.h:492
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
std::string HLSLEntry
The entry point name for HLSL shader being compiled as specified by -E.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:35
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:98
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition Token.h:100
bool isNot(tok::TokenKind K) const
Definition Token.h:99
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5406
Represents a declaration of a type.
Definition Decl.h:3277
void setTypeForDecl(const Type *TD)
Definition Decl.h:3302
const Type * getTypeForDecl() const
Definition Decl.h:3301
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:58
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:331
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:88
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1188
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:77
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:202
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:152
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:234
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2636
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:191
A container of type source information.
Definition Type.h:6655
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:249
QualType getType() const
Return the type wrapped by this type source info.
Definition Type.h:6666
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:532
The base class of the type hierarchy.
Definition Type.h:1577
bool isStructureType() const
Definition Type.cpp:569
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.cpp:1799
bool isDependentSizedArrayType() const
Definition Type.h:7018
bool isBlockPointerType() const
Definition Type.h:6944
bool isVoidType() const
Definition Type.h:7254
bool isBooleanType() const
Definition Type.h:7370
bool isFunctionReferenceType() const
Definition Type.h:6977
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2084
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:1816
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition Type.h:7417
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:666
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:2772
bool isIncompleteArrayType() const
Definition Type.h:7010
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition Type.h:7536
bool isConstantArrayType() const
Definition Type.h:7006
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition Type.h:7397
bool isArrayType() const
Definition Type.h:7002
bool isFunctionPointerType() const
Definition Type.h:6970
bool isPointerType() const
Definition Type.h:6936
const T * castAs() const
Member-template castAs<specific type>.
Definition Type.h:7527
bool isReferenceType() const
Definition Type.h:6948
bool isScalarType() const
Definition Type.h:7341
bool isVariableArrayType() const
Definition Type.h:7014
bool isClkEventT() const
Definition Type.h:7137
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:1975
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:631
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition Type.h:7357
bool isImageType() const
Definition Type.h:7149
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition Type.h:2450
bool isPipeType() const
Definition Type.h:7156
bool isOpenCLSpecificType() const
Definition Type.h:7185
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition Type.h:2345
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2255
bool isHalfType() const
Definition Type.h:7258
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:1928
const RecordType * getAsStructureType() const
Definition Type.cpp:647
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2376
bool containsErrors() const
Whether this type is an error type.
Definition Type.h:2339
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition Type.h:7410
bool isAtomicType() const
Definition Type.h:7077
bool isFunctionProtoType() const
Definition Type.h:2182
bool isObjCIdType() const
Definition Type.h:7097
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition Type.h:2363
bool isObjCObjectType() const
Definition Type.h:7068
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition Type.h:7376
bool isEventT() const
Definition Type.h:7133
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2279
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition Type.h:7477
bool isFunctionType() const
Definition Type.h:6932
bool isObjCObjectPointerType() const
Definition Type.h:7064
bool isMemberFunctionPointerType() const
Definition Type.h:6988
bool isFloatingType() const
Definition Type.cpp:2166
bool isAnyPointerType() const
Definition Type.h:6940
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:1933
bool isSamplerT() const
Definition Type.h:7129
const T * getAs() const
Member-template getAs<specific type>'.
Definition Type.h:7460
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:545
bool isNullPtrType() const
Definition Type.h:7279
bool isRecordType() const
Definition Type.h:7026
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:4343
bool isUnionType() const
Definition Type.cpp:601
bool isFunctionNoProtoType() const
Definition Type.h:2181
bool isReserveIDT() const
Definition Type.h:7145
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.cpp:1807
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.cpp:1803
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3421
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5311
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3319
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3369
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition Decl.h:3385
QualType getUnderlyingType() const
Definition Decl.h:3374
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3381
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition Decl.cpp:5319
TypedefNameDecl * getDecl() const
Definition Type.h:4600
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2195
Expr * getSubExpr() const
Definition Expr.h:2240
Opcode getOpcode() const
Definition Expr.h:2235
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2295
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:989
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1198
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1047
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1071
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1041
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition ExprCXX.cpp:372
The iterator over UnresolvedSets.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3274
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3338
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3045
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:701
void setType(QualType newType)
Definition Decl.h:713
QualType getType() const
Definition Decl.h:712
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5186
Represents a variable declaration or definition.
Definition Decl.h:913
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2724
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2094
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1475
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1519
TLSKind getTLSKind() const
Definition Decl.cpp:2111
bool hasInit() const
Definition Decl.cpp:2342
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1402
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2204
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2133
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2385
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2201
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1528
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:924
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:927
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:921
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2106
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1547
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1240
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1183
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2310
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2410
void setInlineSpecified()
Definition Decl.h:1508
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1165
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1299
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1130
bool checkForConstantInitialization(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the initializer of this variable to determine whether it's a constant initializer.
Definition Decl.cpp:2576
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1501
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1134
const Expr * getInit() const
Definition Decl.h:1325
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1174
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1141
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2370
void setConstexpr(bool IC)
Definition Decl.h:1522
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:936
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:939
void setInit(Expr *I)
Definition Decl.cpp:2401
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2289
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1255
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1252
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1258
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2729
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2189
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1210
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1125
void setImplicitlyInline()
Definition Decl.h:1513
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1426
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1542
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2620
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1219
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2693
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition Decl.h:1436
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition Decl.cpp:2600
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition Type.h:3213
Expr * getSizeExpr() const
Definition Type.h:3232
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:650
bool isVariableCapture() const
Definition ScopeInfo.h:625
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:661
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:714
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:704
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:696
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:683
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1064
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:706
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:102
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:139
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:487
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:148
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:165
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:143
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:156
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:851
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:921
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:840
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:843
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:863
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
const AstTypeMatcher< RecordType > recordType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
constexpr ShaderStage getStageFromEnvironment(const llvm::Triple::EnvironmentType &E)
Definition HLSLRuntime.h:24
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
@ TST_struct
Definition Specifiers.h:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1833
bool isa(CodeGen::Address addr)
Definition Address.h:155
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:203
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:276
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:70
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:80
raw_ostream & operator<<(raw_ostream &OS, const Value &Val)
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:262
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:263
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:59
@ CLanguageLinkage
Definition Linkage.h:60
@ CXXLanguageLinkage
Definition Linkage.h:61
StorageClass
Storage classes.
Definition Specifiers.h:239
@ SC_Auto
Definition Specifiers.h:247
@ SC_PrivateExtern
Definition Specifiers.h:244
@ SC_Extern
Definition Specifiers.h:242
@ SC_Register
Definition Specifiers.h:248
@ SC_Static
Definition Specifiers.h:243
@ SC_None
Definition Specifiers.h:241
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition Specifiers.h:226
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:232
@ TSCS_unspecified
Definition Specifiers.h:227
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:235
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:229
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:272
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:23
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:31
@ ModuleLinkage
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:50
@ ExternalLinkage
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:54
@ C
Languages that the frontend can parse and compile.
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:295
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:93
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:76
ExprResult ExprError()
Definition Ownership.h:278
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ TU_Complete
The translation unit is a complete translation unit.
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:126
MultiVersionKind
Definition Decl.h:1896
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1253
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:189
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:185
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:269
@ CC_X86StdCall
Definition Specifiers.h:271
U cast(CodeGen::Address addr)
Definition Address.h:152
@ None
The alignment was not explicit in code.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:243
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition Visibility.h:33
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:114
@ AS_public
Definition Specifiers.h:115
@ AS_protected
Definition Specifiers.h:116
@ AS_none
Definition Specifiers.h:118
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:38
#define bool
Definition stdbool.h:20
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
SourceLocation getConstQualifierLoc() const
Retrieve the location of the 'const' qualifier.
Definition DeclSpec.h:1483
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1379
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1530
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1465
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1354
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1319
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1212
enum clang::DeclaratorChunk::@210 Kind
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1612
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:161
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1593
FunctionTypeInfo Fun
Definition DeclSpec.h:1591
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1636
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:622
Extra information about a function prototype.
Definition Type.h:4153
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition Type.h:4168
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:55
std::vector< std::string > Features
Definition TargetInfo.h:56
Describes how types, statements, expressions, and declarations should be printed.
SourceLocation PragmaLocation
Definition Sema.h:465
ValueType CurrentValue
Definition Sema.h:669
NamedDecl * Previous
Definition Sema.h:2629
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.